= traceLevel)) {
for(int i=0; i < appenders.length; i++) {
appenders[i].printTrace(classname, level, trace);
}
}
}
/**
* Set the list of appenders
*
* @param appenders List of appenders
*/
public static void setAppenders(Appender[] appenders) {
Logger.appenders = appenders;
}
/**
* Create a static instance
*
* @param classname Classname
* @return Instance
*/
public static synchronized Logger getLogger(String classname) {
return new Logger(classname);
}
/**
* Get the current appenders
*
* @return Array of appender
*/
public static synchronized Appender[] getAppenders() {
return appenders;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/RtpPacket.java
================================================
package de.kp.net.rtp;
/*
* Copyright (C) 2009 The Sipdroid Open Source Project
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of Sipdroid (http://www.sipdroid.org)
*
* Sipdroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* RtpPacket implements a RTP packet.
*/
public class RtpPacket {
/* RTP packet buffer containing both the RTP header and payload */
byte[] packet;
/* RTP packet length */
int packet_len;
/* RTP header length */
// int header_len;
/** Gets the RTP packet */
public byte[] getPacket() {
return packet;
}
/** Gets the RTP packet length */
public int getLength() {
return packet_len;
}
/** Gets the RTP header length */
public int getHeaderLength() {
if (packet_len >= 12)
return 12 + 4 * getCscrCount();
else
return packet_len; // broken packet
}
/** Gets the RTP header length */
public int getPayloadLength() {
if (packet_len >= 12)
return packet_len - getHeaderLength();
else
return 0; // broken packet
}
/** Sets the RTP payload length */
public void setPayloadLength(int len) {
packet_len = getHeaderLength() + len;
}
// version (V): 2 bits
// padding (P): 1 bit
// extension (X): 1 bit
// CSRC count (CC): 4 bits
// marker (M): 1 bit
// payload type (PT): 7 bits
// sequence number: 16 bits
// timestamp: 32 bits
// SSRC: 32 bits
// CSRC list: 0 to 15 items, 32 bits each
/** Gets the version (V) */
public int getVersion() {
if (packet_len >= 12)
return (packet[0] >> 6 & 0x03);
else
return 0; // broken packet
}
/** Sets the version (V) */
public void setVersion(int v) {
if (packet_len >= 12)
packet[0] = (byte) ((packet[0] & 0x3F) | ((v & 0x03) << 6));
}
/** Whether has padding (P) */
public boolean hasPadding() {
if (packet_len >= 12)
return getBit(packet[0], 5);
else
return false; // broken packet
}
/** Set padding (P) */
public void setPadding(boolean p) {
if (packet_len >= 12)
packet[0] = setBit(p, packet[0], 5);
}
/** Whether has extension (X) */
public boolean hasExtension() {
if (packet_len >= 12)
return getBit(packet[0], 4);
else
return false; // broken packet
}
/** Set extension (X) */
public void setExtension(boolean x) {
if (packet_len >= 12)
packet[0] = setBit(x, packet[0], 4);
}
/** Gets the CSCR count (CC) */
public int getCscrCount() {
if (packet_len >= 12)
return (packet[0] & 0x0F);
else
return 0; // broken packet
}
/** Whether has marker (M) */
public boolean hasMarker() {
if (packet_len >= 12)
return getBit(packet[1], 7);
else
return false; // broken packet
}
/** Set marker (M) */
public void setMarker(boolean m) {
if (packet_len >= 12)
packet[1] = setBit(m, packet[1], 7);
}
/** Gets the payload type (PT) */
public int getPayloadType() {
if (packet_len >= 12)
return (packet[1] & 0x7F);
else
return -1; // broken packet
}
/** Sets the payload type (PT) */
public void setPayloadType(int pt) {
if (packet_len >= 12)
packet[1] = (byte) ((packet[1] & 0x80) | (pt & 0x7F));
}
/** Gets the sequence number */
public int getSequenceNumber() {
if (packet_len >= 12)
return getInt(packet, 2, 4);
else
return 0; // broken packet
}
/** Sets the sequence number */
public void setSequenceNumber(int sn) {
if (packet_len >= 12)
setInt(sn, packet, 2, 4);
}
/** Gets the timestamp */
public long getTimestamp() {
if (packet_len >= 12)
return getLong(packet, 4, 8);
else
return 0; // broken packet
}
/** Sets the timestamp */
public void setTimestamp(long timestamp) {
if (packet_len >= 12)
setLong(timestamp, packet, 4, 8);
}
/** Gets the SSCR */
public long getSscr() {
if (packet_len >= 12)
return getLong(packet, 8, 12);
else
return 0; // broken packet
}
/** Sets the SSCR */
public void setSscr(long ssrc) {
if (packet_len >= 12)
setLong(ssrc, packet, 8, 12);
}
/** Gets the CSCR list */
public long[] getCscrList() {
int cc = getCscrCount();
long[] cscr = new long[cc];
for (int i = 0; i < cc; i++)
cscr[i] = getLong(packet, 12 + 4 * i, 16 + 4 * i);
return cscr;
}
/** Sets the CSCR list */
public void setCscrList(long[] cscr) {
if (packet_len >= 12) {
int cc = cscr.length;
if (cc > 15)
cc = 15;
packet[0] = (byte) (((packet[0] >> 4) << 4) + cc);
cscr = new long[cc];
for (int i = 0; i < cc; i++)
setLong(cscr[i], packet, 12 + 4 * i, 16 + 4 * i);
// header_len=12+4*cc;
}
}
/** Sets the payload */
public void setPayload(byte[] payload, int len) {
if (packet_len >= 12) {
int header_len = getHeaderLength();
for (int i = 0; i < len; i++)
packet[header_len + i] = payload[i];
packet_len = header_len + len;
}
}
/** Gets the payload */
public byte[] getPayload() {
int header_len = getHeaderLength();
int len = packet_len - header_len;
byte[] payload = new byte[len];
for (int i = 0; i < len; i++)
payload[i] = packet[header_len + i];
return payload;
}
/** Creates a new RTP packet */
public RtpPacket(byte[] buffer, int packet_length) {
packet = buffer;
packet_len = packet_length;
if (packet_len < 12)
packet_len = 12;
init(0x0F);
}
/** init the RTP packet header (only PT) */
public void init(int ptype) {
init(ptype, RtpRandom.nextLong());
}
/** init the RTP packet header (PT and SSCR) */
public void init(int ptype, long sscr) {
init(ptype, RtpRandom.nextInt(), RtpRandom.nextLong(), sscr);
}
/** init the RTP packet header (PT, SQN, TimeStamp, SSCR) */
public void init(int ptype, int seqn, long timestamp, long sscr) {
setVersion(2);
setPayloadType(ptype);
setSequenceNumber(seqn);
setTimestamp(timestamp);
setSscr(sscr);
}
// *********************** Private and Static ***********************
/** Gets int value */
//private static int getInt(byte b) {
// return ((int) b + 256) % 256;
//}
/** Gets long value */
private static long getLong(byte[] data, int begin, int end) {
long n = 0;
for (; begin < end; begin++) {
n <<= 8;
n += data[begin] & 0xFF;
}
return n;
}
/** Sets long value */
private static void setLong(long n, byte[] data, int begin, int end) {
for (end--; end >= begin; end--) {
data[end] = (byte) (n % 256);
n >>= 8;
}
}
/** Gets Int value */
private static int getInt(byte[] data, int begin, int end) {
return (int) getLong(data, begin, end);
}
/** Sets Int value */
private static void setInt(int n, byte[] data, int begin, int end) {
setLong(n, data, begin, end);
}
/** Gets bit value */
private static boolean getBit(byte b, int bit) {
return (b >> bit) == 1;
}
/** Sets bit value */
private static byte setBit(boolean value, byte b, int bit) {
if (value)
return (byte) (b | (1 << bit));
else
return (byte) ((b | (1 << bit)) ^ (1 << bit));
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/RtpRandom.java
================================================
/*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MjSip is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package de.kp.net.rtp;
/**
* Class Random collects some static methods for generating random numbers and
* other stuff.
*/
public class RtpRandom {
/** The random seed */
static final long seed = System.currentTimeMillis();
// static final long seed=0;
static java.util.Random rand = new java.util.Random(seed);
// static java.util.Random rand=new java.util.Random();
/** Returns a random integer between 0 and n-1 */
/*
* static public int nextInt(int n) { seed=(seed*37)%987654321; return
* (int)(seed%n); }
*/
/** Returns true or false respectively with probability p/100 and (1-p/100) */
/*
* static boolean percent(int p) { return integer(100) receivers;
private RtpSender() {
receivers = new Vector();
}
public int getReceiverCount() {
return receivers.size();
}
public static RtpSender getInstance() {
if (instance == null) instance = new RtpSender();
return instance;
}
/**
* Register RTP packet consumer
*
* @param receiver
*/
public void addReceiver(RtpSocket receiver) {
receivers.add(receiver);
}
/**
* De-register RTP packet consumer
* @param receiver
*/
public void removeReceiver(RtpSocket receiver) {
receivers.remove(receiver);
}
/**
* Send RTP packet to all registered RTP
* packet consumers.
*
* @param rtpPacket
* @throws IOException
*/
public synchronized void send(RtpPacket rtpPacket) throws IOException {
for (RtpSocket receiver:receivers) {
receiver.send(rtpPacket);
}
}
/**
* Send RTP packet to all registered RTP
* packet consumers.
*
* @param rtpPacket
* @throws IOException
*/
public synchronized void send(byte[] data) throws IOException {
for (RtpSocket receiver:receivers) {
receiver.send(data);
}
}
/**
* De-register all registered RTP consumers
*/
public void clear() {
receivers.clear();
}
public void stop() {
// TODO
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/RtpSocket.java
================================================
package de.kp.net.rtp;
/*
* Copyright (C) 2009 The Sipdroid Open Source Project
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of Sipdroid (http://www.sipdroid.org)
*
* Sipdroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.SocketException;
import java.io.IOException;
/**
* RtpSocket implements a RTP socket for receiving and sending RTP packets.
*
* RtpSocket is associated to a DatagramSocket that is used to send and/or
* receive RtpPackets.
*/
public class RtpSocket {
/** UDP socket */
DatagramSocket socket;
DatagramPacket datagram;
/** Remote address */
InetAddress remoteAddress;
/** Remote port */
int remotePort;
/**
* An RtpSocket may be suspended from sending or receiving
* UDP data packets
*/
boolean suspended = false;
/** Creates a new RTP socket (sender and receiver)
* @throws SocketException */
public RtpSocket(InetAddress remoteAddress, int remotePort) throws SocketException {
this.socket = new DatagramSocket();
this.socket.connect(remoteAddress, remotePort);
this.remoteAddress = remoteAddress;
this.remotePort = remotePort;
datagram = new DatagramPacket(new byte[1],1);
}
/** Creates a new RTP socket (sender and receiver) **/
public RtpSocket(DatagramSocket socket, InetAddress remoteAddress, int remotePort) {
this.socket = socket;
// initialize receiver address & port
this.remoteAddress = remoteAddress;
this.remotePort = remotePort;
datagram = new DatagramPacket(new byte[1],1);
}
/** Returns the RTP DatagramSocket */
public DatagramSocket getSocket() {
return this.socket;
}
/** Receives a RTP packet from this socket */
public void receive(RtpPacket rtpPacket) throws IOException {
datagram.setData(rtpPacket.getPacket());
datagram.setLength(rtpPacket.packet.length);
socket.receive(datagram);
if (!socket.isConnected())
socket.connect(datagram.getAddress(), datagram.getPort());
rtpPacket.packet_len = datagram.getLength();
}
/** Sends a RTP packet from this socket */
public void send(RtpPacket rtpPacket) throws IOException {
if (this.suspended == true) return;
datagram.setData(rtpPacket.getPacket());
datagram.setLength(rtpPacket.getLength());
datagram.setAddress(remoteAddress);
datagram.setPort(remotePort);
socket.send(datagram);
}
/** Sends a RTP packet from this socket */
public void send(byte[] data) throws IOException {
if (this.suspended == true) return;
datagram.setData(data);
datagram.setLength(data.length);
datagram.setAddress(remoteAddress);
datagram.setPort(remotePort);
socket.send(datagram);
}
public void suspend(boolean suspended) {
this.suspended = suspended;
}
/** Closes this socket */
public void close() { // socket.close();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/packetizer/AbstractPacketizer.java
================================================
package de.kp.net.rtp.packetizer;
import java.io.IOException;
import java.io.InputStream;
import de.kp.net.rtp.RtpSender;
abstract public class AbstractPacketizer extends Thread {
protected InputStream fis;
protected RtpSender rtpSender;
protected boolean running = false;
public AbstractPacketizer() {
super();
}
public AbstractPacketizer(Runnable runnable) {
super(runnable);
}
public AbstractPacketizer(String threadName) {
super(threadName);
}
public AbstractPacketizer(Runnable runnable, String threadName) {
super(runnable, threadName);
}
public AbstractPacketizer(ThreadGroup group, Runnable runnable) {
super(group, runnable);
}
public AbstractPacketizer(ThreadGroup group, String threadName) {
super(group, threadName);
}
public AbstractPacketizer(ThreadGroup group, Runnable runnable, String threadName) {
super(group, runnable, threadName);
}
public AbstractPacketizer(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
super(group, runnable, threadName, stackSize);
}
public void startStreaming() {
running = true;
start();
}
public void stopStreaming() {
try {
fis.close();
} catch (IOException e) {
}
running = false;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/packetizer/H263Packetizer.java
================================================
package de.kp.net.rtp.packetizer;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import android.os.SystemClock;
import android.util.Log;
import de.kp.net.rtp.RtpPacket;
import de.kp.net.rtp.RtpSender;
import de.kp.net.rtsp.RtspConstants;
public class H263Packetizer extends AbstractPacketizer implements Runnable {
private String TAG = "H263Sender";
private boolean videoQualityHigh = true;
// private int fps;
private boolean change;
public H263Packetizer(InputStream fis) throws SocketException {
this.fis = fis;
this.rtpSender = RtpSender.getInstance();
}
public void run() {
int frame_size = 1400;
byte[] buffer = new byte[frame_size + 14];
buffer[12] = 4;
RtpPacket rtpPacket = new RtpPacket(buffer, 0);
int seqn = 0;
int num, number = 0, src, dest, len = 0, head = 0, lasthead = 0, lasthead2 = 0, cnt = 0, stable = 0;
long now, lasttime = 0;
double avgrate = videoQualityHigh ? 45000 : 24000;
double avglen = avgrate / 20;
rtpPacket.setPayloadType(RtspConstants.RTP_H263_PAYLOADTYPE);
// while (Receiver.listener_video != null && videoValid()) {
while (running) {
num = -1;
try {
num = fis.read(buffer, 14 + number, frame_size - number);
} catch (IOException e) {
Log.w(TAG , e.getMessage());
break;
}
if (num < 0) {
try {
sleep(20);
} catch (InterruptedException e) {
break;
}
continue;
}
number += num;
head += num;
try {
now = SystemClock.elapsedRealtime();
if (lasthead != head + fis.available() && ++stable >= 5 && now - lasttime > 700) {
if (cnt != 0 && len != 0)
avglen = len / cnt;
if (lasttime != 0) {
// fps = (int) ((double) cnt * 1000 / (now - lasttime));
avgrate = (double) ((head + fis.available()) - lasthead2) * 1000 / (now - lasttime);
}
lasttime = now;
lasthead = head + fis.available();
lasthead2 = head;
len = cnt = stable = 0;
}
} catch (IOException e1) {
Log.w(TAG, e1.getMessage());
break;
}
for (num = 14; num <= 14 + number - 2; num++)
if (buffer[num] == 0 && buffer[num + 1] == 0)
break;
if (num > 14 + number - 2) {
num = 0;
rtpPacket.setMarker(false);
} else {
num = 14 + number - num;
rtpPacket.setMarker(true);
}
rtpPacket.setSequenceNumber(seqn++);
rtpPacket.setPayloadLength(number - num + 2);
if (seqn > 10)
try {
rtpSender.send(rtpPacket);
len += number - num;
} catch (IOException e) {
Log.w(TAG, "RTP packet sent failed");
break;
}
if (num > 0) {
num -= 2;
dest = 14;
src = 14 + number - num;
if (num > 0 && buffer[src] == 0) {
src++;
num--;
}
number = num;
while (num-- > 0)
buffer[dest++] = buffer[src++];
buffer[12] = 4;
cnt++;
try {
if (avgrate != 0)
Thread.sleep((int) (avglen / avgrate * 1000));
} catch (Exception e) {
break;
}
rtpPacket.setTimestamp(SystemClock.elapsedRealtime() * 90);
} else {
number = 0;
buffer[12] = 0;
}
if (change) {
change = false;
long time = SystemClock.elapsedRealtime();
try {
while (fis.read(buffer, 14, frame_size) > 0 && SystemClock.elapsedRealtime() - time < 3000)
;
} catch (Exception e) {
}
number = 0;
buffer[12] = 0;
}
}
rtpSender.stop();
try {
while (fis.read(buffer, 0, frame_size) > 0)
;
} catch (IOException e) {
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/packetizer/H264Fifo.java
================================================
/*
* Copyright (C) 2011-2012 GUIGUI Simon, fyhertz@gmail.com
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package de.kp.net.rtp.packetizer;
public class H264Fifo {
private int length = 0, tail = 0, head = 0;
private byte[] buffer;
public H264Fifo(int length) {
this.length = length;
buffer = new byte[length];
}
public void write(byte[] buffer, int offset, int length) {
if (tail+lengthavailable() ? available() : length;
if (head+length=head) ? tail-head : this.length-(head-tail) ;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/packetizer/H264Packetizer.java
================================================
package de.kp.net.rtp.packetizer;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import de.kp.net.rtp.RtpPacket;
import de.kp.net.rtp.RtpSender;
import de.kp.net.rtsp.RtspConstants;
import android.os.SystemClock;
import android.util.Log;
public class H264Packetizer extends AbstractPacketizer implements Runnable {
private final int packetSize = 1400;
private long oldtime = SystemClock.elapsedRealtime(), delay = 20;
private long latency, oldlat = oldtime;
private int available = 0, oldavailable = 0, nalUnitLength = 0, numberNalUnit = 0, len = 0;
private H264Fifo fifo = new H264Fifo(500000);
protected InputStream fis = null;
protected byte[] buffer = new byte[16384 * 2];
protected final int rtpHeaderLength = 12; // Rtp header length
private String TAG = "H264Packetizer";
public H264Packetizer(InputStream fis) throws SocketException {
this.fis = fis;
this.rtpSender = RtpSender.getInstance();
}
public void run() {
int seqn = 0;
byte[] buffer = new byte[16384*2];
RtpPacket rtpPacket = new RtpPacket(buffer, 0);
rtpPacket.setPayloadType(RtspConstants.RTP_H264_PAYLOADTYPE);
// skip the mpeg4 header
try {
// skip all atoms preceding mdat atom
skipMDAT();
// some phones do not set length correctly when stream is not
// seekable, still we need to skip the header
if (len <= 0) {
while (true) {
while (fis.read() != 'm')
;
fis.read(buffer, rtpHeaderLength, 3);
if (buffer[rtpHeaderLength] == 'd' && buffer[rtpHeaderLength + 1] == 'a' && buffer[rtpHeaderLength + 2] == 't')
break;
}
}
len = 0;
} catch (IOException e) {
Log.w(TAG , e.getMessage());
return;
}
while (running) {
/* If there are NAL units in the FIFO ready to be sent, we send one */
// send();
/*
* Read a NAL unit in the FIFO and send it If it is too big, we
* split it in FU-A units (RFC 3984)
*/
int sum = 1, len = 0, nalUnitLength;
if (numberNalUnit != 0) {
/* Read nal unit length (4 bytes) and nal unit header (1 byte) */
len = fifo.read(buffer, rtpHeaderLength, 5);
nalUnitLength = (buffer[rtpHeaderLength + 3] & 0xFF) + (buffer[rtpHeaderLength + 2] & 0xFF) * 256
+ (buffer[rtpHeaderLength + 1] & 0xFF) * 65536;
// Log.d(TAG ,"send- NAL unit length: " + nalUnitLength);
// rsock.updateTimestamp(SystemClock.elapsedRealtime() * 90);
rtpPacket.setTimestamp(SystemClock.elapsedRealtime() * 90);
/* Small nal unit => Single nal unit */
if (nalUnitLength <= packetSize - rtpHeaderLength - 2) {
buffer[rtpHeaderLength] = buffer[rtpHeaderLength + 4];
len = fifo.read(buffer, rtpHeaderLength + 1, nalUnitLength - 1);
rtpPacket.setMarker(true);
try {
rtpPacket.setSequenceNumber(seqn++);
rtpPacket.setPayloadLength(nalUnitLength);
rtpSender.send(rtpPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* Large nal unit => Split nal unit */
else {
/* Set FU-A indicator */
buffer[rtpHeaderLength] = 28;
buffer[rtpHeaderLength] += (buffer[rtpHeaderLength + 4] & 0x60) & 0xFF; // FU indicator
// NRI
// buffer[rtphl] += 0x80;
/* Set FU-A header */
buffer[rtpHeaderLength + 1] = (byte) (buffer[rtpHeaderLength + 4] & 0x1F); // FU header
// type
buffer[rtpHeaderLength + 1] += 0x80; // Start bit
while (sum < nalUnitLength) {
if (!running)
break;
len = fifo.read(buffer,
rtpHeaderLength + 2,
nalUnitLength - sum > packetSize - rtpHeaderLength - 2 ? packetSize - rtpHeaderLength - 2 : nalUnitLength - sum);
sum += len;
if (len < 0)
break;
/* Last packet before next NAL */
if (sum >= nalUnitLength) {
// End bit on
buffer[rtpHeaderLength + 1] += 0x40;
// rsock.markNextPacket();
rtpPacket.setMarker(true);
}
try {
// rsock.send(len + rtpHeaderLength + 2);
rtpPacket.setSequenceNumber(seqn++);
rtpPacket.setPayloadLength(len + 2);
rtpSender.send(rtpPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Switch start bit */
buffer[rtpHeaderLength + 1] = (byte) (buffer[rtpHeaderLength + 1] & 0x7F);
// Log.d(TAG,"send--- FU-A unit, end:"+(boolean)(sum >= nalUnitLength));
}
}
numberNalUnit--;
// Log.d(TAG,"NAL UNIT SENT> " + numberNalUnit);
}
/*
* If the camera has delivered new NAL units we copy them in the
* FIFO Then, the delay between two send call is latency/nbNalu
* with: latency: how long it took to the camera to output new data
* nbNalu: number of NAL units in the FIFO
*/
fillFifo();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
return;
}
}
}
// skip all atoms preceeding mdat atom
private void skipMDAT() throws IOException {
while (true) {
fis.read(buffer, rtpHeaderLength, 8);
if (buffer[rtpHeaderLength + 4] == 'm' && buffer[rtpHeaderLength + 5] == 'd' && buffer[rtpHeaderLength + 6] == 'a' && buffer[rtpHeaderLength + 7] == 't')
break;
len = (buffer[rtpHeaderLength + 3] & 0xFF) + (buffer[rtpHeaderLength + 2] & 0xFF) * 256 + (buffer[rtpHeaderLength + 1] & 0xFF) * 65536;
if (len <= 0)
break;
fis.read(buffer, rtpHeaderLength, len - 8);
}
}
private void fillFifo() {
try {
available = fis.available();
if (available > oldavailable) {
long now = SystemClock.elapsedRealtime();
latency = now - oldlat;
oldlat = now;
oldavailable = available;
}
if (numberNalUnit == 0 && available > 4) {
numberNalUnit = nalUnitLength - len == 0 ? numberNalUnit : numberNalUnit + 1;
} else
return;
while ((available = fis.available()) >= 4) {
fis.read(buffer, rtpHeaderLength, nalUnitLength - len);
fifo.write(buffer, rtpHeaderLength, nalUnitLength - len);
/* Read NAL unit and copy it in the fifo */
len = fis.read(buffer, rtpHeaderLength, 4);
nalUnitLength = (buffer[rtpHeaderLength + 3] & 0xFF) + (buffer[rtpHeaderLength + 2] & 0xFF) * 256
+ (buffer[rtpHeaderLength + 1] & 0xFF) * 65536;
len = fis.read(buffer, rtpHeaderLength + 4, nalUnitLength);
fifo.write(buffer, rtpHeaderLength, len + 4);
if (len == nalUnitLength)
numberNalUnit++;
// Log.i(TAG,"fifo- available: " + available + ", len: " + len + ", naluLength: " + nalUnitLength);
if (fis.available() < 4) {
delay = latency / numberNalUnit;
oldavailable = fis.available();
// Log.i(TAG,"fifo- latency: "+latency+", nbNalu: "+numberNalUnit+", delay: "+delay+" avfifo: "+fifo.available());
}
}
}
catch (IOException e) {
return;
}
}
// Useful for debug
protected String printBuffer(int start,int end) {
String str = "";
for (int i=start;i listeners = new Vector();
/**
* The logger
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
private String TAG = "RtspVideoRecorder";
/**
* Constructor
*/
public RtspVideoRecorder() {
}
/**
* Constructor. Force a video codec.
*
* @param codec Video codec
*/
public RtspVideoRecorder(VideoCodec codec) {
// Set the media codec
setMediaCodec(codec.getMediaCodec());
}
/**
* Constructor. Force a video codec.
*
* @param codec Video codec name
*/
public RtspVideoRecorder(String codec) {
// Set the media codec
for (int i = 0; i < supportedMediaCodecs.length ; i++) {
if (codec.toLowerCase().contains(supportedMediaCodecs[i].getCodecName().toLowerCase())) {
setMediaCodec(supportedMediaCodecs[i]);
break;
}
}
}
/**
* Returns the local RTP port
*
* @return Port
*/
public int getLocalRtpPort() {
return localRtpPort;
}
/**
* Return the video start time
*
* @return Milliseconds
*/
public long getVideoStartTime() {
return videoStartTime;
}
/**
* Is player opened
*
* @return Boolean
*/
public boolean isOpened() {
return opened;
}
/**
* Is player started
*
* @return Boolean
*/
public boolean isStarted() {
return started;
}
/**
* Open the player
*
* @param remoteHost Remote host
* @param remotePort Remote port
*/
public void open(String remoteHost, int remotePort) {
// This is an interface method, that is no longer
// used with the actual context
}
public void open() {
if (opened) {
// Already opened
return;
}
// Check video codec
if (selectedVideoCodec == null) {
if (logger.isActivated()) {
logger.debug("Player error: Video Codec not selected");
}
return;
}
// Init video encoder
try {
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
// H264
NativeH264Encoder.InitEncoder(selectedVideoCodec.getWidth(), selectedVideoCodec.getHeight(), selectedVideoCodec.getFramerate());
} else if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H263Config.CODEC_NAME)) {
// Default H263
NativeH263EncoderParams params = new NativeH263EncoderParams();
params.setEncFrameRate(selectedVideoCodec.getFramerate());
params.setBitRate(selectedVideoCodec.getBitrate());
// set width/height parameters for native encoding, too
params.setEncHeight(selectedVideoCodec.getHeight());
params.setEncWidth(selectedVideoCodec.getWidth());
params.setTickPerSrc(params.getTimeIncRes() / selectedVideoCodec.getFramerate());
params.setIntraPeriod(-1);
params.setNoFrameSkipped(false);
int result = NativeH263Encoder.InitEncoder(params);
if (result != 1) {
if (logger.isActivated()) {
logger.debug("Player error: Encoder init failed with error code " + result);
}
return;
}
}
} catch (UnsatisfiedLinkError e) {
if (logger.isActivated()) {
logger.debug("Player error: " + e.getMessage());
}
return;
}
// Init the RTP layer
try {
rtpInput = new MediaRtpInput();
rtpInput.open();
rtpMediaSender = new MediaRtpSender(videoFormat);
rtpMediaSender.prepareSession(rtpInput);
} catch (Exception e) {
if (logger.isActivated()) {
logger.debug("Player error: " + e.getMessage());
}
return;
}
// Player is opened
opened = true;
}
/**
* Close the player
*/
public void close() {
if (!opened) {
// Already closed
return;
}
// Close the RTP layer
rtpInput.close();
rtpMediaSender.stopSession();
try {
// Close the video encoder
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
NativeH264Encoder.DeinitEncoder();
} else if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H263Config.CODEC_NAME)) {
NativeH263Encoder.DeinitEncoder();
}
} catch (UnsatisfiedLinkError e) {
if (logger.isActivated()) {
logger.error("Can't close correctly the video encoder", e);
}
}
// Player is closed
opened = false;
}
/**
* Start the player
*/
public synchronized void start() {
Log.d(TAG , "start");
if ((opened == false) || (started == true)) {
return;
}
started = true;
// Start RTP layer
rtpMediaSender.startSession();
// Start capture
captureThread.start();
// Player is started
videoStartTime = SystemClock.uptimeMillis();
}
/**
* Stop the player
*/
public void stop() {
if ((opened == false) || (started == false)) {
return;
}
// Stop capture
try {
captureThread.interrupt();
} catch (Exception e) {
}
// Player is stopped
videoStartTime = 0L;
started = false;
}
/**
* Add a media event listener
*
* @param listener Media event listener
*/
public void addListener(IMediaEventListener listener) {
listeners.addElement(listener);
}
/**
* Remove all media event listeners
*/
public void removeAllListeners() {
listeners.removeAllElements();
}
/**
* Get supported media codecs
*
* @return media Codecs list
*/
public MediaCodec[] getSupportedMediaCodecs() {
return supportedMediaCodecs;
}
/**
* Get media codec
*
* @return Media Codec
*/
public MediaCodec getMediaCodec() {
if (selectedVideoCodec == null)
return null;
else
return selectedVideoCodec.getMediaCodec();
}
/**
* Set media codec
*
* @param mediaCodec Media codec
*/
public void setMediaCodec(MediaCodec mediaCodec) {
if (VideoCodec.checkVideoCodec(supportedMediaCodecs, new VideoCodec(mediaCodec))) {
selectedVideoCodec = new VideoCodec(mediaCodec);
videoFormat = (VideoFormat) MediaRegistry.generateFormat(mediaCodec.getCodecName());
// Initialize frame buffer
if (frameBuffer == null) {
frameBuffer = new CameraBuffer();
}
} else {
if (logger.isActivated()) {
logger.debug("Player error: Codec not supported");
}
}
}
/**
* Preview frame from the camera
*
* @param data Frame
* @param camera Camera
*/
public void onPreviewFrame(byte[] data, Camera camera) {
if (frameBuffer != null)
frameBuffer.setFrame(data);
}
/**
* Camera buffer
*/
private class CameraBuffer {
/**
* YUV frame where frame size is always (videoWidth*videoHeight*3)/2
*/
private byte frame[] = new byte[(selectedVideoCodec.getWidth()
* selectedVideoCodec.getHeight() * 3) / 2];
/**
* Set the last captured frame
*
* @param frame Frame
*/
public void setFrame(byte[] frame) {
this.frame = frame;
}
/**
* Return the last captured frame
*
* @return Frame
*/
public byte[] getFrame() {
return frame;
}
}
/**
* Video capture thread
*/
private Thread captureThread = new Thread() {
/**
* Timestamp
*/
private long timeStamp = 0;
/**
* Processing
*/
public void run() {
// if (rtpInput == null) {
// return;
// }
int timeToSleep = 1000 / selectedVideoCodec.getFramerate();
int timestampInc = 90000 / selectedVideoCodec.getFramerate();
byte[] frameData;
byte[] encodedFrame;
long encoderTs = 0;
long oldTs = System.currentTimeMillis();
while (started) {
// Set timestamp
long time = System.currentTimeMillis();
encoderTs = encoderTs + (time - oldTs);
// Get data to encode
frameData = frameBuffer.getFrame();
// Encode frame
int encodeResult;
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
encodedFrame = NativeH264Encoder.EncodeFrame(frameData, encoderTs);
encodeResult = NativeH264Encoder.getLastEncodeStatus();
} else {
encodedFrame = NativeH263Encoder.EncodeFrame(frameData, encoderTs);
encodeResult = 0;
}
System.out.println("RtpVideoRecorder: captureThread: encodeResult == " + encodeResult);
/*
* accept additional status
* EAVCEI_MORE_NAL -- there is more NAL to be retrieved
*/
if ((encodeResult == 0 || encodeResult == 6) && encodedFrame.length > 0) {
if (encodeResult == 6)
System.out.println("RtpVideoRecorder: captureThread: Status == EAVCEI_MORE_NAL");
// Send encoded frame
rtpInput.addFrame(encodedFrame, timeStamp += timestampInc);
}
// Sleep between frames if necessary
long delta = System.currentTimeMillis() - time;
if (delta < timeToSleep) {
try {
Thread.sleep((timeToSleep - delta) - (((timeToSleep - delta) * 10) / 100));
} catch (InterruptedException e) {
}
}
// Update old timestamp
oldTs = time;
}
}
};
/**
* Media RTP input
*/
private static class MediaRtpInput implements MediaInput {
/**
* Received frames
*/
private FifoBuffer fifo = null;
/**
* Constructor
*/
public MediaRtpInput() {
}
/**
* Add a new video frame
*
* @param data Data
* @param timestamp Timestamp
*/
public void addFrame(byte[] data, long timestamp) {
if (fifo != null) {
fifo.addObject(new MediaSample(data, timestamp));
}
}
/**
* Open the player
*/
public void open() {
fifo = new FifoBuffer();
}
/**
* Close the player
*/
public void close() {
if (fifo != null) {
fifo.close();
fifo = null;
}
}
/**
* Read a media sample (blocking method)
*
* @return Media sample
* @throws MediaException
*/
public MediaSample readSample() throws MediaException {
try {
if (fifo != null) {
return (MediaSample)fifo.getObject();
} else {
throw new MediaException("Media input not opened");
}
} catch (Exception e) {
throw new MediaException("Can't read media sample");
}
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/stream/RtpOutputStream.java
================================================
/*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.kp.net.rtp.stream;
import com.orangelabs.rcs.core.ims.protocol.rtp.core.RtcpSession;
import com.orangelabs.rcs.core.ims.protocol.rtp.core.RtpPacket;
import com.orangelabs.rcs.core.ims.protocol.rtp.stream.ProcessorOutputStream;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.Buffer;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.Packet;
import com.orangelabs.rcs.utils.logger.Logger;
import de.kp.net.rtp.RtpSender;
import java.io.IOException;
/**
* RTP output stream
*
* @author Peter Arwanitis (arwanitis@dr-kruscheundpartner.de)
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class RtpOutputStream implements ProcessorOutputStream {
/**
* Sequence number
*/
private int seqNumber = 0;
/**
* RTCP Session
*/
private RtcpSession rtcpSession = null;
/**
* The logger
*/
private final Logger logger = Logger.getLogger(this.getClass().getName());
public RtpOutputStream() {
// Used to build SSCR
rtcpSession = new RtcpSession(true, 16000);
}
public void open() throws Exception {
}
public void close() {
}
/**
* Write to the stream without blocking
*
* @param buffer Input buffer
* @throws IOException
*/
public void write(Buffer buffer) throws IOException {
// Build a RTP packet
RtpPacket packet = buildRtpPacket(buffer);
if (packet == null) return;
// Assemble RTP packet
int size = packet.calcLength();
packet.assemble(size);
// Send the RTP packet to the remote destination
transmit(packet);
}
/**
* Build a RTP packet
*
* @param buffer Input buffer
* @return RTP packet
*/
private RtpPacket buildRtpPacket(Buffer buffer) {
byte data[] = (byte[])buffer.getData();
if (data == null) return null;
Packet packet = new Packet();
packet.data = data;
packet.offset = 0;
packet.length = buffer.getLength();
RtpPacket rtpPacket = new RtpPacket(packet);
if ((buffer.getFlags() & 0x800) != 0) {
rtpPacket.marker = 1;
} else {
rtpPacket.marker = 0;
}
rtpPacket.payloadType = buffer.getFormat().getPayload();
rtpPacket.seqnum = seqNumber++;
rtpPacket.timestamp = buffer.getTimeStamp();
rtpPacket.ssrc = rtcpSession.SSRC;
rtpPacket.payloadoffset = buffer.getOffset();
rtpPacket.payloadlength = buffer.getLength();
return rtpPacket;
}
/**
* Transmit a RTCP compound packet to the remote destination
*
* @param packet RTP packet
* @throws IOException
*/
private void transmit(Packet packet) {
// Prepare data to be sent
byte[] data = packet.data;
if (packet.offset > 0) {
System.arraycopy(data, packet.offset, data = new byte[packet.length], 0, packet.length);
}
// broadcast data
try {
RtpSender.getInstance().send(data);
} catch (IOException e) {
e.printStackTrace();
if (logger.isActivated()) {
logger.error("Can't broadcast the RTP packet", e);
}
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtp/viewer/RtpVideoRenderer.java
================================================
/*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.kp.net.rtp.viewer;
import com.orangelabs.rcs.core.ims.protocol.rtp.MediaRegistry;
import com.orangelabs.rcs.core.ims.protocol.rtp.MediaRtpReceiver;
import com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h263.H263Config;
import com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h263.decoder.NativeH263Decoder;
import com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h264.H264Config;
import com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h264.decoder.NativeH264Decoder;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.video.H263VideoFormat;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.video.H264VideoFormat;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.video.VideoFormat;
import com.orangelabs.rcs.core.ims.protocol.rtp.media.MediaOutput;
import com.orangelabs.rcs.core.ims.protocol.rtp.media.MediaSample;
import com.orangelabs.rcs.platform.network.DatagramConnection;
import com.orangelabs.rcs.platform.network.NetworkFactory;
import com.orangelabs.rcs.service.api.client.media.IMediaEventListener;
import com.orangelabs.rcs.service.api.client.media.IMediaRenderer;
import com.orangelabs.rcs.service.api.client.media.MediaCodec;
import com.orangelabs.rcs.service.api.client.media.video.VideoCodec;
import com.orangelabs.rcs.service.api.client.media.video.VideoSurfaceView;
import com.orangelabs.rcs.utils.logger.Logger;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.client.RtspControl;
import de.kp.net.rtsp.client.message.RtspDescriptor;
import de.kp.net.rtsp.client.message.RtspMedia;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.os.SystemClock;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
/**
* Video RTP renderer. Supports only H.263 and H264 QCIF formats.
*
* @author jexa7410
*/
public class RtpVideoRenderer extends IMediaRenderer.Stub {
/**
* List of supported video codecs
*/
public static MediaCodec[] supportedMediaCodecs = {
new VideoCodec(H264Config.CODEC_NAME, H264VideoFormat.PAYLOAD, H264Config.CLOCK_RATE, H264Config.CODEC_PARAMS,
H264Config.FRAME_RATE, H264Config.BIT_RATE, H264Config.VIDEO_WIDTH,
H264Config.VIDEO_HEIGHT).getMediaCodec(),
new VideoCodec(H263Config.CODEC_NAME, H263VideoFormat.PAYLOAD, H263Config.CLOCK_RATE, H263Config.CODEC_PARAMS,
H263Config.FRAME_RATE, H263Config.BIT_RATE, H263Config.VIDEO_WIDTH,
H263Config.VIDEO_HEIGHT).getMediaCodec()
};
/**
* Selected video codec
*/
private VideoCodec selectedVideoCodec = null;
/**
* Video format
*/
private VideoFormat videoFormat;
/**
* Local RTP port
*/
private int localRtpPort;
/**
* RTP receiver session
*/
private MediaRtpReceiver rtpReceiver = null;
/**
* RTP media output
*/
private MediaRtpOutput rtpOutput = null;
/**
* Is player opened
*/
private boolean opened = false;
/**
* Is player started
*/
private boolean started = false;
/**
* Video start time
*/
private long videoStartTime = 0L;
/**
* Video surface
*/
private VideoSurfaceView surface = null;
/**
* Media event listeners
*/
private Vector listeners = new Vector();
/**
* The logger
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Temporary connection to reserve the port
*/
private DatagramConnection temporaryConnection = null;
/**
* RTSP Control
*/
private RtspControl rtspControl;
/**
* Constructor Force a RTSP Server Uri
* @throws Exception
*/
public RtpVideoRenderer(String uri) throws Exception {
/*
* The RtspControl opens a connection to an RtspServer, that
* is determined by the URI provided.
*/
rtspControl = new RtspControl(uri);
/*
* wait unit the rtspControl has achieved status READY; in this
* state, an SDP file is present and is ready to get evaluated
*/
while (rtspControl.getState() != RtspConstants.READY) {
; // blocking
}
/*
* Set the local RTP port: this is the (socket)
* port, the RtspVideoRenderer is listening to
* (UDP) RTP packets.
*/
// localRtpPort = NetworkRessourceManager.generateLocalRtpPort();
localRtpPort = rtspControl.getClientPort();
reservePort(localRtpPort);
/*
* The media resources associated with the SDP descriptor are
* evaluated and the respective video encoding determined
*/
RtspDescriptor rtspDescriptor = rtspControl.getDescriptor();
List mediaList = rtspDescriptor.getMediaList();
if (mediaList.size() == 0) throw new Exception("The session description contains no media resource.");
RtspMedia videoResource = null;
for (RtspMedia mediaItem:mediaList) {
if (mediaItem.getMediaType().equals(RtspConstants.SDP_VIDEO_TYPE)) {
videoResource = mediaItem;
break;
}
}
if (videoResource == null) throw new Exception("The session description contains no video resource.");
String codec = videoResource.getEncoding();
if (codec == null) throw new Exception("No encoding provided for video resource.");
// Set the media codec
for (int i = 0; i < supportedMediaCodecs.length; i++) {
if (codec.toLowerCase().contains(supportedMediaCodecs[i].getCodecName().toLowerCase())) {
setMediaCodec(supportedMediaCodecs[i]);
break;
}
}
}
/**
* Set the surface to render video
*
* @param surface Video surface
*/
public void setVideoSurface(VideoSurfaceView surface) {
this.surface = surface;
}
/**
* Return the video start time
*
* @return Milliseconds
*/
public long getVideoStartTime() {
return videoStartTime;
}
/**
* Returns the local RTP port
*
* @return Port
*/
public int getLocalRtpPort() {
return localRtpPort;
}
/**
* Reserve a port.
*
* @param port the port to reserve
*/
private void reservePort(int port) {
if (temporaryConnection != null) return;
try {
temporaryConnection = NetworkFactory.getFactory().createDatagramConnection();
temporaryConnection.open(port);
} catch (IOException e) {
temporaryConnection = null;
}
}
/**
* Release the reserved port; this method
* is invoked while preparing the RTP layer
*/
private void releasePort() {
if (temporaryConnection == null) return;
try {
temporaryConnection.close();
} catch (IOException e) {
temporaryConnection = null;
}
}
/**
* Is player opened
*
* @return Boolean
*/
public boolean isOpened() {
return opened;
}
/**
* Is player started
*
* @return Boolean
*/
public boolean isStarted() {
return started;
}
/**
* Open the renderer
*/
public void open() {
if (opened) {
// Already opened
return;
}
// Check video codec
if (selectedVideoCodec == null) {
if (logger.isActivated()) {
logger.debug("Player error: Video Codec not selected");
}
return;
}
try {
// Init the video decoder
int result;
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
result = NativeH264Decoder.InitDecoder();
} else { // default H263
result = NativeH263Decoder.InitDecoder(selectedVideoCodec.getWidth(), selectedVideoCodec.getHeight());
}
if (result == 0) {
if (logger.isActivated()) {
logger.debug("Player error: Decoder init failed with error code " + result);
}
return;
}
} catch (UnsatisfiedLinkError e) {
if (logger.isActivated()) {
logger.debug("Player error: " + e.getMessage());
}
return;
}
try {
// initialize RTP layer
releasePort();
rtpOutput = new MediaRtpOutput();
rtpOutput.open();
rtpReceiver = new MediaRtpReceiver(localRtpPort);
rtpReceiver.prepareSession(rtpOutput, videoFormat);
} catch (Exception e) {
if (logger.isActivated()) {
logger.debug("Player error: " + e.getMessage());
}
return;
}
// Player is opened
opened = true;
}
/**
* Close the renderer
*/
public void close() {
if (opened == false) return;
// Send TEARDOWN request to RTSP Server
rtspControl.stop();
// Close the RTP layer
rtpReceiver.stopSession();
rtpOutput.close();
// Close the video decoder
closeVideoDecoder();
// Player is closed
opened = false;
}
public void closeVideoDecoder() {
try {
// Close the video decoder
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
NativeH264Decoder.DeinitDecoder();
} else { // default H263
NativeH263Decoder.DeinitDecoder();
}
} catch (UnsatisfiedLinkError e) {
if (logger.isActivated()) {
logger.error("Can't close correctly the video decoder", e);
}
}
}
/**
* Start the RTP layer (i.e listen to the reserved local
* port for RTP packets), and send a PLAY request to the
* RTSP server
*/
public void start() {
if ((opened == false) || (started == true)) {
return;
}
// Start RTP layer
rtpReceiver.startSession();
// Send PLAY request to RTSP Server
rtspControl.play();
/*
* wait unit the rtspControl has achieved status PLAYING
*/
while (rtspControl.getState() != RtspConstants.PLAYING) {
; // blocking
}
// Renderer is started
videoStartTime = SystemClock.uptimeMillis();
started = true;
}
/**
* Stop the renderer
*/
public void stop() {
if (started == false) return;
// Send TEARDOWN request to RTSP Server
rtspControl.stop();
// Stop RTP layer
if (rtpReceiver != null) rtpReceiver.stopSession();
if (rtpOutput != null) rtpOutput.close();
// Force black screen
surface.clearImage();
// Close the video decoder
closeVideoDecoder();
// Renderer is stopped
started = false;
videoStartTime = 0L;
}
/**
* Add a media event listener
*
* @param listener Media event listener
*/
public void addListener(IMediaEventListener listener) {
listeners.addElement(listener);
}
/**
* Remove all media event listeners
*/
public void removeAllListeners() {
listeners.removeAllElements();
}
/**
* Get supported media codecs
*
* @return media Codecs list
*/
public MediaCodec[] getSupportedMediaCodecs() {
return supportedMediaCodecs;
}
/**
* Get media codec
*
* @return Media codec
*/
public MediaCodec getMediaCodec() {
if (selectedVideoCodec == null)
return null;
else
return selectedVideoCodec.getMediaCodec();
}
/**
* Set media codec
*
* @param mediaCodec Media codec
*/
public void setMediaCodec(MediaCodec mediaCodec) {
if (VideoCodec.checkVideoCodec(supportedMediaCodecs, new VideoCodec(mediaCodec))) {
selectedVideoCodec = new VideoCodec(mediaCodec);
videoFormat = (VideoFormat) MediaRegistry.generateFormat(mediaCodec.getCodecName());
} else {
if (logger.isActivated()) {
logger.debug("Player error: Codec not supported");
}
}
}
/**
* Media RTP output
*/
private class MediaRtpOutput implements MediaOutput {
/**
* Video frame
*/
private int decodedFrame[];
/**
* Bitmap frame
*/
private Bitmap rgbFrame;
/**
* Constructor
*/
public MediaRtpOutput() {
decodedFrame = new int[selectedVideoCodec.getWidth() * selectedVideoCodec.getHeight()];
rgbFrame = Bitmap.createBitmap(selectedVideoCodec.getWidth(), selectedVideoCodec.getHeight(), Bitmap.Config.RGB_565);
}
/**
* Open the renderer
*/
public void open() {
}
/**
* Close the renderer
*/
public void close() {
}
/**
* Write a media sample
*
* @param sample Sample
*/
public void writeSample(MediaSample sample) {
if (selectedVideoCodec.getCodecName().equalsIgnoreCase(H264Config.CODEC_NAME)) {
if (NativeH264Decoder.DecodeAndConvert(sample.getData(), decodedFrame) == 1) {
rgbFrame.setPixels(decodedFrame, 0, selectedVideoCodec.getWidth(), 0, 0,
selectedVideoCodec.getWidth(), selectedVideoCodec.getHeight());
if (surface != null) {
surface.setImage(rgbFrame);
}
} else {
System.out.println("MediaRtpOutput.writeSample: cannot decode sample >len:" + sample.getLength());
}
} else { // default H263
if (NativeH263Decoder.DecodeAndConvert(sample.getData(), decodedFrame, sample.getTimeStamp()) == 1) {
rgbFrame.setPixels(decodedFrame, 0, selectedVideoCodec.getWidth(), 0, 0,
selectedVideoCodec.getWidth(), selectedVideoCodec.getHeight());
if (surface != null) {
surface.setImage(rgbFrame);
}
}
}
}
}
@Override
public void open(String remoteHost, int remotePort) throws RemoteException {
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/RtspConstants.java
================================================
package de.kp.net.rtsp;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.util.Log;
public class RtspConstants {
// rtsp states
public static int INIT = 0;
public static int READY = 1;
public static int PLAYING = 2;
public static int UNDEFINED = 3;
// rtsp message types
public static int OPTIONS = 3;
public static int DESCRIBE = 4;
public static int SETUP = 5;
public static int PLAY = 6;
public static int PAUSE = 7;
public static int TEARDOWN = 8;
public static String SDP_AUDIO_TYPE = "audio";
public static String SDP_VIDEO_TYPE = "video";
// the payload type is part of the SDP description
// sent back as an answer to a DESCRIBE request.
// android actually supports video streaming from
// the camera using H.263-1998
// TODO: sync with
// com.orangelabs.rcs.core.ims.protocol.rtp.format.video.H263VideoFormat.PAYLOAD = 97
// com.orangelabs.rcs.core.ims.protocol.rtp.format.video.H264VideoFormat.PAYLOAD = 96
public static int RTP_H264_PAYLOADTYPE = 96; // dynamic range
public static int RTP_H263_PAYLOADTYPE = 97; // dynamic range
public static String H263_1998 = "H263-1998/90000";
public static String H263_2000 = "H263-2000/90000";
public static String H264 = "H264/90000";
public static enum VideoEncoder {
H263_ENCODER,
H264_ENCODER
};
// TODO: synchronize settings
// com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h263.H263Config
// com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h264.H264Config
// QCIF
// public static String WIDTH = "176";
// public static String HEIGHT = "144";
// QCIF
public static String WIDTH = "352";
public static String HEIGHT = "288";
public static final int FPS = 15;
public static final int BITRATE = 128000; // h263-2000
//public static final int BITRATE = 64000; // for h264
public static final String SEP = " ";
// default client ports for audio and video streaming;
// the port is usually provided with an RTSP request
public static final int CLIENT_AUDIO_PORT = 2000;
public static final int CLIENT_VIDEO_PORT = 4000;
// public static String SERVER_IP = "spexhd2:8080";
public static int SERVER_PORT = 8080;
public static String SERVER_IP = getLocalIpAddress() + ":" + SERVER_PORT;
public static String SERVER_NAME = "KuP RTSP Server";
public static String SERVER_VERSION = "0.1";
public static int PORT_BASE = 3000;
public static int[] PORTS_RTSP_RTP = {PORT_BASE, (PORT_BASE + 1)};
public static final String DIR_MULTIMEDIA = "../";
// tags for logging
public static String SERVER_TAG = "RtspServer";
public static String getLocalIpAddress() {
// http://www.droidnova.com/get-the-ip-address-of-your-device,304.html
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("RtspConstants", ex.toString());
}
return null;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/RtspClient.java
================================================
package de.kp.net.rtsp.client;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import de.kp.net.rtsp.client.api.RequestListener;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.api.MessageFactory;
import de.kp.net.rtsp.client.api.Request;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.api.Transport;
import de.kp.net.rtsp.client.api.TransportListener;
import de.kp.net.rtsp.client.header.RtspHeader;
import de.kp.net.rtsp.client.header.SessionHeader;
import de.kp.net.rtsp.client.header.TransportHeader;
import de.kp.net.rtsp.client.header.TransportHeader.LowerTransport;
import de.kp.net.rtsp.client.message.MessageBuffer;
import de.kp.net.rtsp.client.message.RtspMessageFactory;
import de.kp.net.rtsp.client.request.RtspOptionsRequest;
import de.kp.net.rtsp.client.request.RtspRequest;
public class RtspClient implements TransportListener {
private Transport transport;
private MessageFactory messageFactory;
private MessageBuffer messageBuffer;
private volatile int cseq;
private SessionHeader session;
/**
* URI kept from last setup.
*/
private URI uri;
private Map outstanding;
private RequestListener clientListener;
public RtspClient() {
cseq = 0;
messageFactory = new RtspMessageFactory();
messageBuffer = new MessageBuffer();
outstanding = new HashMap();
}
public Transport getTransport() {
return transport;
}
public void setSession(SessionHeader session) {
this.session = session;
}
public MessageFactory getMessageFactory() {
return messageFactory;
}
public URI getURI() {
return uri;
}
public void options(String uri, URI endpoint) {
try {
RtspOptionsRequest message = (RtspOptionsRequest) messageFactory.outgoingRequest(uri, RtspRequest.Method.OPTIONS, nextCSeq());
// if (getTransport().isConnected() == false) message.addHeader(new RtspHeader("Connection", "close"));
send(message, endpoint);
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void play() {
try {
send(messageFactory.outgoingRequest(uri.toString(), RtspRequest.Method.PLAY, nextCSeq(), session));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void pause() {
try {
send(messageFactory.outgoingRequest(uri.toString(), RtspRequest.Method.PAUSE, nextCSeq(), session));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void record() throws IOException {
throw new UnsupportedOperationException("Recording is not supported in current version.");
}
public void setRequestListener(RequestListener listener) {
clientListener = listener;
}
public RequestListener getRequestListener() {
return clientListener;
}
public void setTransport(Transport transport) {
this.transport = transport;
transport.setTransportListener(this);
}
public void describe(URI uri, String resource) {
this.uri = uri;
String finalURI = uri.toString();
if ((resource != null) && (resource.equals("*") == false))
finalURI += '/' + resource;
try {
send(messageFactory.outgoingRequest(finalURI, RtspRequest.Method.DESCRIBE, nextCSeq(), new RtspHeader("Accept", "application/sdp")));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void setup(URI uri, int localPort) {
this.uri = uri;
try {
String portParam = "client_port=" + localPort + "-" + (1 + localPort);
send(getSetup(uri.toString(), localPort, new TransportHeader(LowerTransport.DEFAULT, "unicast", portParam), session));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void setup(URI uri, int localPort, String resource) {
this.uri = uri;
try {
String portParam = "client_port=" + localPort + "-" + (1 + localPort);
String finalURI = uri.toString();
if ((resource != null) && (resource.equals("*") == false))
finalURI += '/' + resource;
send(getSetup(finalURI, localPort, new TransportHeader(LowerTransport.DEFAULT, "unicast", portParam), session));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void teardown() {
if(session == null)
return;
try {
send(messageFactory.outgoingRequest(uri.toString(), RtspRequest.Method.TEARDOWN, nextCSeq(), session, new RtspHeader("Connection", "close")));
} catch(Exception e) {
if(clientListener != null) clientListener.onError(this, e);
}
}
public void dataReceived(Transport t, byte[] data, int size) throws Throwable {
messageBuffer.addData(data, size);
while(messageBuffer.getLength() > 0)
try
{
messageFactory.incomingMessage(messageBuffer);
messageBuffer.discardData();
Message message = messageBuffer.getMessage();
if(message instanceof RtspRequest)
send(messageFactory.outgoingResponse(405, "Method Not Allowed",
message.getCSeq().getValue()));
else
{
RtspRequest request = null;
synchronized(outstanding)
{
request = outstanding.remove(message.getCSeq().getValue());
}
Response response = (Response) message;
request.handleResponse(this, response);
clientListener.onSuccess(this, request, response);
}
} catch(Exception e)
{
messageBuffer.discardData();
if(clientListener != null)
clientListener.onError(this, e.getCause());
}
}
@Override
public void dataSent(Transport t) throws Throwable
{
}
@Override
public void error(Transport t, Throwable error) {
clientListener.onError(this, error);
}
@Override
public void error(Transport t, Message message, Throwable error)
{
clientListener.onFailure(this, (RtspRequest) message, error);
}
@Override
public void remoteDisconnection(Transport t) throws Throwable
{
synchronized(outstanding)
{
for(Map.Entry request : outstanding.entrySet())
clientListener.onFailure(this, request.getValue(),
new SocketException("Socket has been closed"));
}
}
public int nextCSeq() {
return cseq++;
}
public void send(Message message) throws Exception {
send(message, uri);
}
private void send(Message message, URI endpoint) throws Exception
{
if(!transport.isConnected())
transport.connect(endpoint);
if(message instanceof RtspRequest)
{
RtspRequest request = (RtspRequest) message;
synchronized(outstanding)
{
outstanding.put(message.getCSeq().getValue(), request);
}
try
{
transport.sendMessage(message);
} catch(IOException e)
{
clientListener.onFailure(this, request, e);
}
} else
transport.sendMessage(message);
}
private Request getSetup(String uri, int localPort, RtspHeader... headers) throws URISyntaxException {
return getMessageFactory().outgoingRequest(uri, RtspRequest.Method.SETUP, nextCSeq(),
headers);
}
@Override
public void connected(Transport t) throws Throwable {
// TODO Auto-generated method stub
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/RtspControl.java
================================================
package de.kp.net.rtsp.client;
import java.net.URI;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.client.api.RequestListener;
import de.kp.net.rtsp.client.api.Request;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.message.RtspDescriptor;
import de.kp.net.rtsp.client.message.RtspMedia;
import de.kp.net.rtsp.client.transport.TCPTransport;
public class RtspControl implements RequestListener {
// reference to the RTSP client
private RtspClient client;
// flag to indicate whether there is a connection
// established to a remote RTSP server
private boolean connected = false;
// reference to the RTSP server URI
private URI uri;
private int port;
private String resource;
// reference to the SDP file returned as a response
// to a DESCRIBE request
private RtspDescriptor rtspDescriptor;
private int state;
/**
* This constructor is invoked with an uri that
* describes the server uri and also a certain
* resource
*/
public RtspControl(String uri) {
int pos = uri.lastIndexOf("/");
try {
this.uri = new URI(uri.substring(0, pos));
this.resource = uri.substring(pos+1);
// initialize the RTSP communication
this.client = new RtspClient();
this.client.setTransport(new TCPTransport());
this.client.setRequestListener(this);
this.state = RtspConstants.UNDEFINED;
// the OPTIONS request is used to invoke and
// test the connection to the RTSP server,
// specified with the URI provided
this.client.options("*", this.uri);
} catch (Exception e) {
if (this.client != null) {
onError(this.client, e);
} else {
e.printStackTrace();
}
}
}
public RtspControl(String uri, String resource) {
try {
this.uri = new URI(uri);
this.resource = resource;
// initialize the RTSP communication
this.client = new RtspClient();
this.client.setTransport(new TCPTransport());
this.client.setRequestListener(this);
this.state = RtspConstants.UNDEFINED;
// the OPTIONS request is used to invoke and
// test the connection to the RTSP server,
// specified with the URI provided
this.client.options("*", this.uri);
} catch (Exception e) {
if (this.client != null) {
onError(this.client, e);
} else {
e.printStackTrace();
}
}
}
public void play() {
if ((this.client == null) || (this.connected == false)) return;
if (this.state == RtspConstants.READY) {
this.client.play();
}
}
public void pause() {
if ((this.client == null) || (this.connected == false)) return;
if (this.state == RtspConstants.PLAYING) {
this.client.pause();
}
}
public void stop() {
if ((this.client == null) || (this.connected == false)) return;
// send TEARDOWN request
this.client.teardown();
}
public boolean isConnected() {
return this.connected;
}
public int getState() {
return this.state;
}
public int getClientPort() {
return this.port;
}
public RtspDescriptor getDescriptor() {
return this.rtspDescriptor;
}
@Override
public void onError(RtspClient client, Throwable error) {
if ((this.client != null) && (this.connected == true)) {
this.client.teardown();
}
this.state = RtspConstants.UNDEFINED;
this.connected = false;
this.client = null;
}
// register SDP file
public void onDescriptor(RtspClient client, String descriptor) {
this.rtspDescriptor = new RtspDescriptor(descriptor);
}
public void onFailure(RtspClient client, Request request, Throwable cause) {
if ((this.client != null) && (this.connected == true)) {
this.client.teardown();
}
this.state = RtspConstants.UNDEFINED;
this.connected = false;
this.client = null;
}
public void onSuccess(RtspClient client, Request request, Response response) {
try {
if ((this.client != null) && (response.getStatusCode() == 200)) {
Request.Method method = request.getMethod();
if (method == Request.Method.OPTIONS) {
// the response to an OPTIONS request
this.connected = true;
// send DESCRIBE request
this.client.describe(this.uri, this.resource);
} else if (method == Request.Method.DESCRIBE) {
// set state to INIT
this.state = RtspConstants.INIT;
/*
* onSuccess is called AFTER onDescriptor method;
* this implies, that a media resource is present
* with a certain client port specified by the RTSP
* server
*/
RtspMedia video = this.rtspDescriptor.getFirstVideo();
if (video != null) {
this.port = Integer.valueOf(video.getTransportPort());
// send SETUP request
this.client.setup(this.uri, this.port, this.resource);
}
} else if (method == Request.Method.SETUP) {
// set state to READY
this.state = RtspConstants.READY;
} else if (method == Request.Method.PLAY) {
// set state to PLAYING
this.state = RtspConstants.PLAYING;
} else if (method == Request.Method.PAUSE) {
// set state to READY
this.state = RtspConstants.READY;
} else if (method == Request.Method.TEARDOWN) {
this.connected = false;
// set state to UNDEFINED
this.state = RtspConstants.UNDEFINED;
}
} else {
}
} catch (Exception e) {
onError(this.client, e);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/EntityMessage.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.header.RtspContent;
public interface EntityMessage {
public RtspContent getContent();
public void setContent(RtspContent content);
public Message getMessage();
public byte[] getBytes() throws Exception;
public boolean isEntity();
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/Message.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.header.CSeqHeader;
import de.kp.net.rtsp.client.header.RtspHeader;
public interface Message {
static String RTSP_TOKEN = "RTSP/";
static String RTSP_VERSION = "1.0";
static String RTSP_VERSION_TOKEN = RTSP_TOKEN + RTSP_VERSION;
/**
*
* @return the Message line (the first line of the message)
*/
public String getLine();
/**
* Returns a header, if exists
*
* @param name
* Name of the header to be searched
* @return value of that header
* @throws Exception
*/
public RtspHeader getHeader(String name) throws Exception;
/**
* Convenience method to get CSeq.
*
* @return
*/
public CSeqHeader getCSeq();
/**
*
* @return all headers in the message, except CSeq
*/
public RtspHeader[] getHeaders();
/**
* Adds a new header or replaces if one already exists. If header to be added
* is a CSeq, implementation MUST keep reference of this header.
*
* @param header
*/
public void addHeader(RtspHeader header);
/**
*
* @return message as a byte array, ready for transmission.
*/
public byte[] getBytes() throws Exception;
/**
*
* @return Entity part of message, it exists.
*/
public EntityMessage getEntityMessage();
/**
*
* @param entity
* adds an entity part to the message.
* @return this, for easier construction.
*/
public Message setEntityMessage(EntityMessage entity);
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/MessageFactory.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.header.RtspContent;
import de.kp.net.rtsp.client.header.RtspHeader;
import de.kp.net.rtsp.client.message.MessageBuffer;
public interface MessageFactory {
public void incomingMessage(MessageBuffer message) throws Exception;
public Request outgoingRequest(String uri, Request.Method method, int cseq, RtspHeader... extras) throws URISyntaxException;
public Request outgoingRequest(RtspContent body, String uri, Request.Method method, int cseq, RtspHeader... extras) throws URISyntaxException;
public Response outgoingResponse(int code, String message, int cseq, RtspHeader... extras);
public Response outgoingResponse(RtspContent body, int code, String text, int cseq, RtspHeader... extras);
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/Request.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.RtspClient;
public interface Request extends Message {
enum Method {
OPTIONS, DESCRIBE, SETUP, PLAY, PAUSE, RECORD, TEARDOWN
};
public void setLine(Method method, String uri) throws URISyntaxException;
public Method getMethod();
public String getURI();
public void handleResponse(RtspClient client, Response response);
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/RequestListener.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.RtspClient;
public interface RequestListener {
public void onDescriptor(RtspClient client, String descriptor);
public void onError(RtspClient client, Throwable error);
public void onFailure(RtspClient client, Request request, Throwable cause);
public void onSuccess(RtspClient client, Request request, Response response);
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/Response.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public interface Response extends Message {
public void setLine(int statusCode, String statusPhrase);
public int getStatusCode();
public String getStatusText();
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/Transport.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.io.IOException;
import java.net.URI;
/**
* This interface defines a transport protocol (TCP, UDP) or method (HTTP
* tunneling). Transport also MUST enqueue a command if a connection is busy at
* the moment it is issued.
*/
public interface Transport {
public void connect(URI to) throws IOException;
public void disconnect();
public void sendMessage(Message message) throws Exception;
public void setTransportListener(TransportListener listener);
public void setUserData(Object data);
public boolean isConnected();
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/api/TransportListener.java
================================================
package de.kp.net.rtsp.client.api;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
/**
* Listener for transport events. Implementations of {@link Transport}, when
* calling a listener method, must catch all errors and submit them to the
* error() method.
*/
public interface TransportListener {
public void connected(Transport t) throws Throwable;
public void error(Transport t, Throwable error);
public void error(Transport t, Message message, Throwable error);
public void remoteDisconnection(Transport t) throws Throwable;
public void dataReceived(Transport t, byte[] data, int size) throws Throwable;
public void dataSent(Transport t) throws Throwable;
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/CSeqHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class CSeqHeader extends RtspBaseIntegerHeader {
public static final String NAME = "CSeq";
public CSeqHeader() {
super(NAME);
}
public CSeqHeader(int cseq) {
super(NAME, cseq);
}
public CSeqHeader(String line) {
super(line);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/ContentEncodingHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class ContentEncodingHeader extends RtspBaseStringHeader {
public static final String NAME = "Content-Encoding";
public ContentEncodingHeader() {
super(NAME);
}
public ContentEncodingHeader(String header) {
super(NAME, header);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/ContentLengthHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class ContentLengthHeader extends RtspBaseIntegerHeader {
public static final String NAME = "Content-Length";
public ContentLengthHeader() {
super(NAME);
}
public ContentLengthHeader(int value) {
super(NAME, value);
}
public ContentLengthHeader(String header) throws Exception {
super(NAME, header);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/ContentTypeHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class ContentTypeHeader extends RtspBaseStringHeader {
public static final String NAME = "Content-Type";
public ContentTypeHeader() {
super(NAME);
}
public ContentTypeHeader(String header) {
super(NAME, header);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/RtspBaseIntegerHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class RtspBaseIntegerHeader extends RtspHeader {
private int value;
public RtspBaseIntegerHeader(String name) {
super(name);
String text = getRawValue();
if(text != null) value = Integer.parseInt(text);
}
public RtspBaseIntegerHeader(String name, int value) {
super(name);
setValue(value);
}
public RtspBaseIntegerHeader(String name, String header) throws Exception {
super(header);
checkName(name);
value = Integer.parseInt(getRawValue());
}
public final void setValue(int newValue) {
value = newValue;
setRawValue(String.valueOf(value));
}
public final int getValue() {
return value;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/RtspBaseStringHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class RtspBaseStringHeader extends RtspHeader {
public RtspBaseStringHeader(String name) {
super(name);
}
public RtspBaseStringHeader(String name, String header) {
super(header);
try {
checkName(name);
} catch(Exception e) {
setName(name);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/RtspContent.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.api.Message;
public class RtspContent {
private String type;
private String encoding;
private byte[] content;
public void setDescription(Message message) throws Exception {
type = message.getHeader(ContentTypeHeader.NAME).getRawValue();
try {
encoding = message.getHeader(ContentEncodingHeader.NAME).getRawValue();
} catch(Exception e) {
}
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public byte[] getBytes() {
return content;
}
public void setBytes(byte[] content) {
this.content = content;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/RtspHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class RtspHeader {
private String name;
private String value;
/**
* Constructs a new header.
*
* @param header
* if the character ':' (colon) is not found, it will be the name of
* the header. Otherwise, this constructor parses the header line.
*/
public RtspHeader(String header) {
int colon = header.indexOf(':');
if(colon == -1)
name = header;
else {
name = header.substring(0, colon);
value = header.substring(++colon).trim();
}
}
public RtspHeader(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getRawValue() {
return value;
}
public void setRawValue(String value) {
this.value = value;
}
public String toString() {
return name + ": " + value;
}
public boolean equals(Object obj) {
if(super.equals(obj))
return true;
if(obj instanceof String)
return getName().equals(obj);
if(obj instanceof RtspHeader)
return getName().equals(((RtspHeader) obj).getName());
return false;
}
protected final void checkName(String expected) throws Exception {
if(expected.equalsIgnoreCase(getName()) == false)
throw new Exception("[Header Mismatch] - Expected: " + expected + " Retrieved: " + getName());
}
protected final void setName(String name) {
value = this.name;
this.name = name;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/SessionHeader.java
================================================
package de.kp.net.rtsp.client.header;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class SessionHeader extends RtspBaseStringHeader {
public static final String NAME = "Session";
public SessionHeader() {
super(NAME);
}
public SessionHeader(String header) {
super(NAME, header);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/header/TransportHeader.java
================================================
package de.kp.net.rtsp.client.header;
/*
Copyright 2010 Voice Technology Ind. e Com. Ltda.
This file is part of RTSPClientLib.
RTSPClientLib is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTSPClientLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with RTSPClientLib. If not, see .
*/
import java.util.Arrays;
import java.util.List;
/**
* Models a "Transport" header from RFC 2326. According to specification, there may be parameters, which will be inserted as a list of strings, which follow below:
*
parameter = ( "unicast" | "multicast" )
| ";" "destination" [ "=" address ]
| ";" "interleaved" "=" channel [ "-" channel ]
| ";" "append"
| ";" "ttl" "=" ttl
| ";" "layers" "=" 1*DIGIT
| ";" "port" "=" port [ "-" port ]
| ";" "client_port" "=" port [ "-" port ]
| ";" "server_port" "=" port [ "-" port ]
| ";" "ssrc" "=" ssrc
| ";" "mode" = <"> 1\#mode <">
ttl = 1*3(DIGIT)
port = 1*5(DIGIT)
ssrc = 8*8(HEX)
channel = 1*3(DIGIT)
address = host
mode = <"> *Method <"> | Method
* @author paulo
*
*/
public class TransportHeader extends RtspHeader {
public static final String NAME = "Transport";
public static enum LowerTransport {
TCP, UDP, DEFAULT
};
private LowerTransport transport;
private List parameters;
public TransportHeader(String header)
{
super(header);
String value = getRawValue();
if(!value.startsWith("RTP/AVP"))
throw new IllegalArgumentException("Missing RTP/AVP");
int index = 7;
if(value.charAt(index) == '/')
{
switch(value.charAt(++index))
{
case 'T':
transport = LowerTransport.TCP;
break;
case 'U':
transport = LowerTransport.UDP;
break;
default:
throw new IllegalArgumentException("Invalid Transport: "
+ value.substring(7));
}
index += 3;
} else
transport = LowerTransport.DEFAULT;
if(value.charAt(index) != ';' && index != value.length())
throw new IllegalArgumentException("Parameter block expected");
addParameters(value.substring(++index).split(";"));
}
public TransportHeader(LowerTransport transport, String... parameters)
{
super(NAME);
this.transport = transport;
addParameters(parameters);
}
public String getParameter(String part)
{
for(String parameter : parameters)
if(parameter.startsWith(part))
return parameter;
throw new IllegalArgumentException("No such parameter named " + part);
}
void addParameters(String[] parameterList)
{
if(parameters == null)
parameters = Arrays.asList(parameterList);
else
parameters.addAll(Arrays.asList(parameterList));
}
LowerTransport getTransport()
{
return transport;
}
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder(NAME).append(": ").append("RTP/AVP");
if(transport != LowerTransport.DEFAULT)
buffer.append('/').append(transport);
for(String parameter : parameters)
buffer.append(';').append(parameter);
return buffer.toString();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/MessageBuffer.java
================================================
package de.kp.net.rtsp.client.message;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.api.Message;
public class MessageBuffer {
/**
* buffer for received data
*/
private byte[] data;
/**
* offset for starting useful area
*/
private int offset;
/**
* length of useful portion.
*/
private int length;
/**
* Used (read) buffer.
*/
private int used;
/**
* {@link Message} created during last parsing.
*/
private Message message;
/**
* Adds more data to buffer and ensures the sequence [data, newData] is
* contiguous.
*
* @param newData data to be added to the buffer.
*/
public void addData(byte[] newData, int newLength) {
if (data == null) {
data = newData;
length = newLength;
offset = 0;
} else {
// buffer seems to be small.
if((data.length - offset - length) < newLength) {
// try to sequeeze data at the beginning of the buffer only if current
// buffer does not overlap
if(offset >= length && (data.length - length) >= newLength) {
System.arraycopy(data, offset, data, 0, length);
offset = 0;
} else { // worst-case scenario, a new buffer will have to be created
byte[] temp = new byte[data.length + newLength];
System.arraycopy(data, offset, temp, 0, length);
offset = 0;
data = temp;
}
}
// there's room for everything - just copy
System.arraycopy(newData, 0, data, offset + length, newLength);
length += newLength;
}
}
/**
* Discards used portions of the buffer.
*/
public void discardData() {
offset += used;
length -= used;
}
public byte[] getData() {
return data;
}
public int getOffset() {
return offset;
}
public int getLength() {
return length;
}
public void setMessage(Message message) {
this.message = message;
}
public Message getMessage() {
return message;
}
public void setused(int used) {
this.used = used;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/RtspDescriptor.java
================================================
package de.kp.net.rtsp.client.message;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import de.kp.net.rtsp.RtspConstants;
public class RtspDescriptor {
private static String SEP = "\r\n";
private ArrayList mediaList;
public RtspDescriptor(String descriptor) {
// initialize media list
mediaList = new ArrayList();
RtspMedia mediaItem = null;
try {
StringTokenizer tokenizer = new StringTokenizer(descriptor, SEP);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.startsWith("m=")) {
// a new media item is detected
mediaItem = new RtspMedia(token);
mediaList.add(mediaItem);
} else if (token.startsWith("a=")) {
mediaItem.setAttribute(token);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public List getMediaList() {
return mediaList;
}
public RtspMedia getFirstVideo() {
RtspMedia video = null;
for (RtspMedia mediaItem:this.mediaList) {
if (mediaItem.getMediaType().equals(RtspConstants.SDP_VIDEO_TYPE)) {
video = mediaItem;
break;
}
}
return video;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/RtspEntityMessage.java
================================================
package de.kp.net.rtsp.client.message;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.api.EntityMessage;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.header.RtspContent;
import de.kp.net.rtsp.client.header.ContentEncodingHeader;
import de.kp.net.rtsp.client.header.ContentLengthHeader;
import de.kp.net.rtsp.client.header.ContentTypeHeader;
public class RtspEntityMessage implements EntityMessage {
private RtspContent content;
private final Message message;
public RtspEntityMessage(Message message) {
this.message = message;
}
public RtspEntityMessage(Message message, RtspContent body) {
this(message);
setContent(body);
}
@Override
public Message getMessage() {
return message;
};
public byte[] getBytes() throws Exception {
message.getHeader(ContentTypeHeader.NAME);
message.getHeader(ContentLengthHeader.NAME);
return content.getBytes();
}
@Override
public RtspContent getContent() {
return content;
}
@Override
public void setContent(RtspContent content) {
if(content == null) throw new NullPointerException();
this.content = content;
message.addHeader(new ContentTypeHeader(content.getType()));
if(content.getEncoding() != null)
message.addHeader(new ContentEncodingHeader(content.getEncoding()));
message.addHeader(new ContentLengthHeader(content.getBytes().length));
}
@Override
public boolean isEntity() {
return content != null;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/RtspMedia.java
================================================
package de.kp.net.rtsp.client.message;
public class RtspMedia {
private String mediaType;
private String mediaFormat;
private String transportPort;
private String transportProtocol;
private String encoding;
private String clockrate;
private String framerate;
private static String SDP_CONTROL = "a=control:";
private static String SDP_RANGE = "a=range:";
private static String SDP_LENGTH = "a=length:";
private static String SDP_RTMAP = "a=rtpmap:";
private static String SDP_FRAMERATE = "a=framerate:";
public RtspMedia(String line) {
String[] tokens = line.substring(2).split(" ");
mediaType = tokens[0];
mediaFormat = tokens[3];
transportPort = tokens[1];
transportProtocol = tokens[2];
}
public String getMediaType() {
return mediaType;
}
public String getFrameRate() {
return framerate;
}
public String getEncoding() {
return encoding;
}
public String getClockrate() {
return clockrate;
}
public String getTransportPort() {
return transportPort;
}
public void setAttribute(String line) throws Exception {
if (line.startsWith(SDP_CONTROL)) {
} else if (line.startsWith(SDP_RANGE)) {
} else if (line.startsWith(SDP_LENGTH)) {
} else if (line.startsWith(SDP_FRAMERATE)) {
framerate = line.substring(SDP_FRAMERATE.length());
} else if (line.startsWith(SDP_RTMAP)) {
String[] tokens = line.substring(SDP_RTMAP.length()).split(" ");
String payloadType = tokens[0];
if (payloadType.equals(mediaFormat) == false) throw new Exception("Corrupted Session Description - Payload Type");
if (tokens[1].contains("/")) {
String[] subtokens = tokens[1].split("/");
encoding = subtokens[0];
clockrate = subtokens[1];
} else {
encoding = tokens[1];
}
}
}
public String toString() {
return mediaType + " " + transportPort + " " + transportProtocol + " " + mediaFormat + " " +
encoding + "/" + clockrate;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/RtspMessage.java
================================================
package de.kp.net.rtsp.client.message;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.util.ArrayList;
import java.util.List;
import de.kp.net.rtsp.client.api.EntityMessage;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.header.CSeqHeader;
import de.kp.net.rtsp.client.header.RtspHeader;
public abstract class RtspMessage implements Message {
private String line;
private List headers;
private CSeqHeader cseq;
private EntityMessage entity;
public RtspMessage() {
headers = new ArrayList();
}
@Override
public byte[] getBytes() throws Exception {
getHeader(CSeqHeader.NAME);
addHeader(new RtspHeader("User-Agent", "RtspClient"));
byte[] message = toString().getBytes();
if (getEntityMessage() != null) {
byte[] body = entity.getBytes();
byte[] full = new byte[message.length + body.length];
System.arraycopy(message, 0, full, 0, message.length);
System.arraycopy(body, 0, full, message.length, body.length);
message = full;
}
return message;
}
@Override
public RtspHeader getHeader(final String name) throws Exception {
int index = headers.indexOf(new Object() {
@Override
public boolean equals(Object obj) {
return name.equalsIgnoreCase(((RtspHeader) obj).getName());
}
});
if(index == -1) throw new Exception("[Missing Header] " + name);
return headers.get(index);
}
@Override
public RtspHeader[] getHeaders() {
return headers.toArray(new RtspHeader[headers.size()]);
}
@Override
public CSeqHeader getCSeq() {
return cseq;
}
@Override
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
@Override
public void addHeader(RtspHeader header) {
if(header == null) return;
if(header instanceof CSeqHeader)
cseq = (CSeqHeader) header;
int index = headers.indexOf(header);
if(index > -1)
headers.remove(index);
else
index = headers.size();
headers.add(index, header);
}
@Override
public EntityMessage getEntityMessage() {
return entity;
}
@Override
public Message setEntityMessage(EntityMessage entity) {
this.entity = entity;
return this;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(getLine()).append("\r\n");
for(RtspHeader header : headers)
buffer.append(header).append("\r\n");
buffer.append("\r\n");
return buffer.toString();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/message/RtspMessageFactory.java
================================================
package de.kp.net.rtsp.client.message;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.api.MessageFactory;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.header.CSeqHeader;
import de.kp.net.rtsp.client.header.RtspContent;
import de.kp.net.rtsp.client.header.ContentEncodingHeader;
import de.kp.net.rtsp.client.header.ContentLengthHeader;
import de.kp.net.rtsp.client.header.ContentTypeHeader;
import de.kp.net.rtsp.client.header.RtspHeader;
import de.kp.net.rtsp.client.header.SessionHeader;
import de.kp.net.rtsp.client.header.TransportHeader;
import de.kp.net.rtsp.client.request.RtspDescribeRequest;
import de.kp.net.rtsp.client.request.RtspOptionsRequest;
import de.kp.net.rtsp.client.request.RtspPauseRequest;
import de.kp.net.rtsp.client.request.RtspPlayRequest;
import de.kp.net.rtsp.client.request.RtspRequest;
import de.kp.net.rtsp.client.request.RtspSetupRequest;
import de.kp.net.rtsp.client.request.RtspTeardownRequest;
import de.kp.net.rtsp.client.response.RtspResponse;
public class RtspMessageFactory implements MessageFactory {
private static Map> headerMap;
private static Map> requestMap;
static {
headerMap = new HashMap>();
requestMap = new HashMap>();
try {
putHeader(ContentEncodingHeader.class);
putHeader(ContentLengthHeader.class);
putHeader(ContentTypeHeader.class);
putHeader(CSeqHeader.class);
putHeader(SessionHeader.class);
putHeader(TransportHeader.class);
requestMap.put(RtspRequest.Method.OPTIONS, RtspOptionsRequest.class);
requestMap.put(RtspRequest.Method.SETUP, RtspSetupRequest.class);
requestMap.put(RtspRequest.Method.TEARDOWN, RtspTeardownRequest.class);
requestMap.put(RtspRequest.Method.DESCRIBE, RtspDescribeRequest.class);
requestMap.put(RtspRequest.Method.PLAY, RtspPlayRequest.class);
requestMap.put(RtspRequest.Method.PAUSE, RtspPauseRequest.class);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putHeader(Class extends RtspHeader> cls) throws Exception {
headerMap.put(cls.getDeclaredField("NAME").get(null).toString().toLowerCase(), cls.getConstructor(String.class));
}
/**
* This method handles RTSP server responses
*/
public void incomingMessage(MessageBuffer buffer) throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(buffer.getData(), buffer.getOffset(), buffer.getLength());
int initial = in.available();
Message message = null;
try {
// message line.
String line = readLine(in);
if (line.startsWith(Message.RTSP_TOKEN)) {
message = new RtspResponse(line);
} else {
RtspRequest.Method method = null;
try {
method = RtspRequest.Method.valueOf(line.substring(0, line.indexOf(' ')));
} catch (IllegalArgumentException ilae) {
}
Class extends RtspRequest> cls = requestMap.get(method);
if (cls != null)
message = cls.getConstructor(String.class).newInstance(line);
else
message = new RtspRequest(line);
}
while (true)
{
line = readLine(in);
if (in == null)
throw new Exception();
if (line.length() == 0)
break;
Constructor extends RtspHeader> c = headerMap.get(line.substring(0,
line.indexOf(':')).toLowerCase());
if (c != null)
message.addHeader(c.newInstance(line));
else
message.addHeader(new RtspHeader(line));
}
buffer.setMessage(message);
try
{
int length = ((ContentLengthHeader) message
.getHeader(ContentLengthHeader.NAME)).getValue();
if (in.available() < length)
throw new Exception();
RtspContent content = new RtspContent();
content.setDescription(message);
byte[] data = new byte[length];
in.read(data);
content.setBytes(data);
message.setEntityMessage(new RtspEntityMessage(message, content));
} catch (Exception e)
{
}
} catch (Exception e)
{
throw new Exception(e);
} finally
{
buffer.setused(initial - in.available());
try
{
in.close();
} catch (IOException e)
{
}
}
}
@Override
public RtspRequest outgoingRequest(String uri, RtspRequest.Method method, int cseq, RtspHeader... extras) throws URISyntaxException {
Class extends RtspRequest> cls = requestMap.get(method);
RtspRequest message;
try {
message = cls != null ? cls.newInstance() : new RtspRequest();
} catch (Exception e) {
throw new RuntimeException(e);
}
message.setLine(method, uri);
fillMessage(message, cseq, extras);
return message;
}
@Override
public RtspRequest outgoingRequest(RtspContent body, String uri, RtspRequest.Method method, int cseq, RtspHeader... extras) throws URISyntaxException {
Message message = outgoingRequest(uri, method, cseq, extras);
return (RtspRequest) message.setEntityMessage(new RtspEntityMessage(message, body));
}
@Override
public Response outgoingResponse(int code, String text, int cseq, RtspHeader... extras) {
RtspResponse message = new RtspResponse();
message.setLine(code, text);
fillMessage(message, cseq, extras);
return message;
}
@Override
public Response outgoingResponse(RtspContent body, int code, String text, int cseq, RtspHeader... extras) {
Message message = outgoingResponse(code, text, cseq, extras);
return (Response) message.setEntityMessage(new RtspEntityMessage(message, body));
}
private void fillMessage(Message message, int cseq, RtspHeader[] extras) {
message.addHeader(new CSeqHeader(cseq));
for (RtspHeader h : extras)
message.addHeader(h);
}
private String readLine(InputStream in) throws IOException {
int ch = 0;
StringBuilder b = new StringBuilder();
for (ch = in.read(); ch != -1 && ch != 0x0d && ch != 0x0a; ch = in.read())
b.append((char) ch);
if (ch == -1)
return null;
in.read();
return b.toString();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspDescribeRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.RtspClient;
import de.kp.net.rtsp.client.api.Response;
public class RtspDescribeRequest extends RtspRequest {
public RtspDescribeRequest() {
super();
}
public RtspDescribeRequest(String messageLine) throws URISyntaxException {
super(messageLine);
}
@Override
public byte[] getBytes() throws Exception {
getHeader("Accept");
return super.getBytes();
}
@Override
public void handleResponse(RtspClient client, Response response) {
super.handleResponse(client, response);
try {
client.getRequestListener().onDescriptor(client, new String(response.getEntityMessage().getContent().getBytes()));
} catch(Exception e) {
client.getRequestListener().onError(client, e);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspOptionsRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URI;
import java.net.URISyntaxException;
public class RtspOptionsRequest extends RtspRequest {
public RtspOptionsRequest() {
}
public RtspOptionsRequest(String line) throws URISyntaxException {
super(line);
}
@Override
public void setLine(Method method, String uri) throws URISyntaxException {
setMethod(method);
setURI("*".equals(uri) ? uri : new URI(uri).toString());
super.setLine(method.toString() + ' ' + uri + ' ' + RTSP_VERSION_TOKEN);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspPauseRequest.java
================================================
package de.kp.net.rtsp.client.request;
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.header.SessionHeader;
public class RtspPauseRequest extends RtspRequest {
public RtspPauseRequest() {
}
public RtspPauseRequest(String messageLine) throws URISyntaxException {
super(messageLine);
}
@Override
public byte[] getBytes() throws Exception {
getHeader(SessionHeader.NAME);
return super.getBytes();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspPlayRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.header.SessionHeader;
public class RtspPlayRequest extends RtspRequest {
public RtspPlayRequest() {
}
public RtspPlayRequest(String messageLine) throws URISyntaxException {
super(messageLine);
}
@Override
public byte[] getBytes() throws Exception {
getHeader(SessionHeader.NAME);
return super.getBytes();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URI;
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.RtspClient;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.api.Request;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.message.RtspMessage;
public class RtspRequest extends RtspMessage implements Request {
private Method method;
private String uri;
public RtspRequest() {
}
public RtspRequest(String messageLine) throws URISyntaxException {
String[] parts = messageLine.split(" ");
setLine(Method.valueOf(parts[0]), parts[1]);
}
@Override
public void setLine(Method method, String uri) throws URISyntaxException {
this.method = method;
this.uri = new URI(uri).toString();
;
super.setLine(method.toString() + ' ' + uri + ' ' + RTSP_VERSION_TOKEN);
}
@Override
public Method getMethod() {
return method;
}
@Override
public String getURI() {
return uri;
}
@Override
public void handleResponse(RtspClient client, Response response) {
if (testForClose(client, this) || testForClose(client, response))
client.getTransport().disconnect();
}
protected void setURI(String uri) {
this.uri = uri;
}
protected void setMethod(Method method) {
this.method = method;
}
private boolean testForClose(RtspClient client, Message message) {
try {
return message.getHeader("Connection").getRawValue().equalsIgnoreCase("close");
} catch(Exception e) {
// this is an expected exception in case of no
// connection close in the response message
// client.getRequestListener().onError(client, e);
}
return false;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspSetupRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.RtspClient;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.header.SessionHeader;
public class RtspSetupRequest extends RtspRequest {
public RtspSetupRequest() {
}
public RtspSetupRequest(String line) throws URISyntaxException {
super(line);
}
@Override
public byte[] getBytes() throws Exception {
getHeader("Transport");
return super.getBytes();
}
@Override
public void handleResponse(RtspClient client, Response response) {
super.handleResponse(client, response);
try {
if(response.getStatusCode() == 200)
client.setSession((SessionHeader) response.getHeader(SessionHeader.NAME));
} catch(Exception e) {
client.getRequestListener().onError(client, e);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/request/RtspTeardownRequest.java
================================================
package de.kp.net.rtsp.client.request;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.net.URISyntaxException;
import de.kp.net.rtsp.client.RtspClient;
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.header.SessionHeader;
public class RtspTeardownRequest extends RtspRequest {
public RtspTeardownRequest() {
super();
}
public RtspTeardownRequest(String messageLine) throws URISyntaxException {
super(messageLine);
}
@Override
public byte[] getBytes() throws Exception {
getHeader(SessionHeader.NAME);
return super.getBytes();
}
@Override
public void handleResponse(RtspClient client, Response response) {
super.handleResponse(client, response);
if(response.getStatusCode() == 200) client.setSession(null);
client.getTransport().disconnect();
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/response/RtspResponse.java
================================================
package de.kp.net.rtsp.client.response;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.api.Response;
import de.kp.net.rtsp.client.message.RtspMessage;
public class RtspResponse extends RtspMessage implements Response {
private int status;
private String text;
public RtspResponse() {
}
public RtspResponse(String line) {
setLine(line);
line = line.substring(line.indexOf(' ') + 1);
status = Integer.parseInt(line.substring(0, line.indexOf(' ')));
text = line.substring(line.indexOf(' ') + 1);
}
@Override
public int getStatusCode() {
return status;
}
@Override
public String getStatusText() {
return text;
}
@Override
public void setLine(int statusCode, String statusText) {
status = statusCode;
text = statusText;
super.setLine(RTSP_VERSION_TOKEN + ' ' + status + ' ' + text);
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/transport/TCPTransport.java
================================================
package de.kp.net.rtsp.client.transport;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.api.Transport;
import de.kp.net.rtsp.client.api.TransportListener;
class TCPTransportThread extends Thread {
private final TCPTransport transport;
private volatile TCPTransportListener listener;
public TCPTransportThread(TCPTransport transport, TransportListener listener) {
this.transport = transport;
this.listener = new TCPTransportListener(listener);
}
public TCPTransportListener getListener() {
return listener;
}
public void setListener(TransportListener listener) {
listener = new TCPTransportListener(listener);
}
@Override
public void run() {
listener.connected(transport);
byte[] buffer = new byte[2048];
int read = -1;
while(transport.isConnected()) {
try {
read = transport.receive(buffer);
if(read == -1)
{
transport.setConnected(false);
listener.remoteDisconnection(transport);
} else
listener.dataReceived(transport, buffer, read);
} catch(IOException e) {
listener.error(transport, e);
}
}
}
}
public class TCPTransport implements Transport {
private Socket socket;
private TCPTransportThread thread;
private TransportListener transportListener;
private volatile boolean connected;
public TCPTransport() {
}
@Override
public void connect(URI to) throws IOException {
if(connected)
throw new IllegalStateException("Socket is still open. Close it first");
int port = to.getPort();
if(port == -1) port = 554;
socket = new Socket(to.getHost(), port);
setConnected(true);
thread = new TCPTransportThread(this, transportListener);
thread.start();
}
@Override
public void disconnect() {
setConnected(false);
try {
socket.close();
} catch(IOException e) {
}
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public synchronized void sendMessage(Message message) throws Exception {
socket.getOutputStream().write(message.getBytes());
thread.getListener().dataSent(this);
}
@Override
public void setTransportListener(TransportListener listener) {
transportListener = listener;
if(thread != null)
thread.setListener(listener);
}
@Override
public void setUserData(Object data) {
}
int receive(byte[] data) throws IOException {
return socket.getInputStream().read(data);
}
void setConnected(boolean connected) {
this.connected = connected;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/client/transport/TCPTransportListener.java
================================================
package de.kp.net.rtsp.client.transport;
/**
* Copyright 2010 Voice Technology Ind. e Com. Ltda.
*
* RTSPClientLib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* RTSPClientLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see .
*
*
* This class has been adapted to the needs of the RtspCamera project
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
import de.kp.net.rtsp.client.api.Message;
import de.kp.net.rtsp.client.api.Transport;
import de.kp.net.rtsp.client.api.TransportListener;
class TCPTransportListener implements TransportListener {
private final TransportListener behaviour;
public TCPTransportListener(TransportListener theBehaviour) {
behaviour = theBehaviour;
}
@Override
public void connected(Transport t) {
if (behaviour != null)
try {
behaviour.connected(t);
} catch(Throwable error) {
behaviour.error(t, error);
}
}
@Override
public void dataReceived(Transport t, byte[] data, int size) {
if (behaviour != null)
try {
behaviour.dataReceived(t, data, size);
} catch(Throwable error) {
behaviour.error(t, error);
}
}
@Override
public void dataSent(Transport t) {
// TODO Auto-generated method stub
if (behaviour != null)
try {
behaviour.dataSent(t);
} catch(Throwable error) {
behaviour.error(t, error);
}
}
@Override
public void error(Transport t, Throwable error) {
if (behaviour != null)
behaviour.error(t, error);
}
@Override
public void error(Transport t, Message message, Throwable error) {
if(behaviour != null)
behaviour.error(t, message, error);
}
@Override
public void remoteDisconnection(Transport t) {
if (behaviour != null)
try {
behaviour.remoteDisconnection(t);
} catch(Throwable error) {
behaviour.error(t, error);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/RtspServer.java
================================================
package de.kp.net.rtsp.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import android.util.Log;
import de.kp.net.rtp.RtpSender;
import de.kp.net.rtp.RtpSocket;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.RtspConstants.VideoEncoder;
import de.kp.net.rtsp.server.response.Parser;
import de.kp.net.rtsp.server.response.RtspDescribeResponse;
import de.kp.net.rtsp.server.response.RtspError;
import de.kp.net.rtsp.server.response.RtspOptionsResponse;
import de.kp.net.rtsp.server.response.RtspPauseResponse;
import de.kp.net.rtsp.server.response.RtspPlayResponse;
import de.kp.net.rtsp.server.response.RtspResponse;
import de.kp.net.rtsp.server.response.RtspResponseTeardown;
import de.kp.net.rtsp.server.response.RtspSetupResponse;
/**
* This class describes a RTSP streaming
* server for Android platforms. RTSP is
* used to control video streaming from
* a remote user agent.
*
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class RtspServer implements Runnable {
// reference to the server socket
private ServerSocket serverSocket;
// indicator to determine whether the server has stopped or not
private boolean stopped = false;
// inidicator to describe whether the server all of its threads
// are terminated
private boolean terminated = false;
// reference to the video encoder (H263, H264) used over RTP
private VideoEncoder encoder;
// a temporary cache to manage all threads initiated by the RTSP server
private Vector serverThreads;
public RtspServer(int port, VideoEncoder encoder) throws IOException {
this.serverThreads = new Vector();
this.encoder = encoder;
this.serverSocket = new ServerSocket(port);
}
public void run() {
/*
* In order to communicate with different clients,
* we construct a thread for each client that is
* connected.
*/
while (this.stopped == false) {
try {
Socket clientSocket = this.serverSocket.accept();
serverThreads.add(new ServerThread(clientSocket, this.encoder));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isTerminated() {
return this.terminated;
}
/**
* This method is used to stop the RTSP server
*/
public void stop() {
this.stopped = true;
terminate();
try {
this.serverSocket.close();
} catch (IOException e) {
// nothing todo
}
}
/**
* This method is used to tear down all threads that have
* been invoked by the RTSP server during life time
*/
private void terminate() {
for (Thread serverThread:serverThreads) {
if (serverThread.isAlive()) serverThread.interrupt();
}
this.terminated = true;
}
private class ServerThread extends Thread {
private String TAG = "RtspServer";
// response to RTSP client
private RtspResponse rtspResponse;
private String contentBase = "";
/*
* input and output stream buffer for TCP connection;
* UDP response are sent through DatagramSocket
*/
private BufferedReader rtspBufferedReader;
private BufferedWriter rtspBufferedWriter;
private int rtspState;
// Sequence number of RTSP messages within the session
private int cseq = 0;
private int clientPort;
// remote (client) address
private InetAddress clientAddress;
/*
* This datagram socket is used to send UDP
* packets to the clientIPAddress
*/
private RtpSocket rtpSocket;
private final Socket clientSocket;
private VideoEncoder encoder;
public ServerThread(Socket socket, VideoEncoder encoder) {
this.clientSocket = socket;
this.encoder = encoder;
// register IP address of requesting client
this.clientAddress = this.clientSocket.getInetAddress();
start();
}
public void run() {
// prepare server response
String response = "";
try {
// Set input and output stream filters
rtspBufferedReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()) );
rtspBufferedWriter = new BufferedWriter(new OutputStreamWriter(this.clientSocket.getOutputStream()) );
boolean setup = false;
while (setup == false) {
// determine request type and also provide
// server response
int requestType = getRequestType();
// send response
response = rtspResponse.toString();
rtspBufferedWriter.write(response);
rtspBufferedWriter.flush();
if (requestType == RtspConstants.SETUP) {
setup = true;
// update RTSP state
rtspState = RtspConstants.READY;
// in case of a setup request, we create a new RtpSocket
// instance used to send RtpPacket
this.rtpSocket = new RtpSocket(this.clientAddress, this.clientPort);
// this RTP socket is registered as RTP receiver to also
// receive the streaming video of this device
RtpSender.getInstance().addReceiver(this.rtpSocket);
}
}
// this is an endless loop, that is terminated an
// with interrupt sent to the respective thread
while (true) {
// pares incoming request to decide how to proceed
int requestType = getRequestType();
// send response
response = rtspResponse.toString();
rtspBufferedWriter.write(response);
rtspBufferedWriter.flush();
if ((requestType == RtspConstants.PLAY) && (rtspState == RtspConstants.READY)) {
Log.i(TAG, "request: PLAY");
// make sure that the respective client socket is
// ready to send RTP packets
this.rtpSocket.suspend(false);
this.rtspState = RtspConstants.PLAYING;
} else if ((requestType == RtspConstants.PAUSE) && (rtspState == RtspConstants.PLAYING)) {
Log.i(TAG, "request: PAUSE");
// suspend RTP socket from sending video packets
this.rtpSocket.suspend(true);
} else if (requestType == RtspConstants.TEARDOWN) {
Log.i(TAG, "request: TEARDOWN");
// this RTP socket is removed from the RTP Sender
RtpSender.getInstance().removeReceiver(this.rtpSocket);
// close the clienr socket for receiving incoming RTSP request
this.clientSocket.close();
// close the associated RTP socket for sending RTP packets
this.rtpSocket.close();
}
// the pattern below enables an interrupt
// which allows to close this thread
try {
sleep(20);
} catch (InterruptedException e) {
break;
}
}
} catch(Throwable t) {
t.printStackTrace();
System.out.println("Caught " + t + " - closing thread");
}
}
private int getRequestType() throws Exception {
int requestType = -1;
// retrieve the request in a string representation
// for later evaluation
String requestLine = "";
try {
requestLine = Parser.readRequest(rtspBufferedReader);
} catch (IOException e) {
e.printStackTrace();
}
Log.i(TAG, "requestLine: " + requestLine);
// determine request type from incoming RTSP request
requestType = Parser.getRequestType(requestLine);
if (contentBase.isEmpty()) {
contentBase = Parser.getContentBase(requestLine);
}
if (!requestLine.isEmpty()) {
cseq = Parser.getCseq(requestLine);
}
if (requestType == RtspConstants.OPTIONS) {
rtspResponse = new RtspOptionsResponse(cseq);
} else if (requestType == RtspConstants.DESCRIBE) {
buildDescribeResponse(requestLine);
} else if (requestType == RtspConstants.SETUP) {
buildSetupResponse(requestLine);
} else if (requestType == RtspConstants.PAUSE) {
rtspResponse = new RtspPauseResponse(cseq);
} else if (requestType == RtspConstants.TEARDOWN) {
rtspResponse = new RtspResponseTeardown(cseq);
} else if (requestType == RtspConstants.PLAY) {
rtspResponse = new RtspPlayResponse(cseq);
String range = Parser.getRangePlay(requestLine);
if (range != null) ((RtspPlayResponse) rtspResponse).setRange(range);
} else {
if( requestLine.isEmpty()){
rtspResponse = new RtspError(cseq);
} else {
rtspResponse = new RtspError(cseq);
}
}
return requestType;
}
/**
* Create an RTSP response for an incoming SETUP request.
*
* @param requestLine
* @throws Exception
*/
private void buildSetupResponse(String requestLine) throws Exception {
rtspResponse = new RtspSetupResponse(cseq);
// client port
clientPort = Parser.getClientPort(requestLine);
((RtspSetupResponse) rtspResponse).setClientPort(clientPort);
// transport protocol
((RtspSetupResponse) rtspResponse).setTransportProtocol(Parser.getTransportProtocol(requestLine));
// session type
((RtspSetupResponse) rtspResponse).setSessionType(Parser.getSessionType(requestLine));
((RtspSetupResponse) rtspResponse).setClientIP(this.clientAddress.getHostAddress());
int[] interleaved = Parser.getInterleavedSetup(requestLine);
if(interleaved != null){
((RtspSetupResponse) rtspResponse).setInterleaved(interleaved);
}
}
/**
* Create an RTSP response for an incoming DESCRIBE request.
*
* @param requestLine
* @throws Exception
*/
private void buildDescribeResponse(String requestLine) throws Exception{
rtspResponse = new RtspDescribeResponse(cseq);
// set file name
String fileName = Parser.getFileName(requestLine);
((RtspDescribeResponse) rtspResponse).setFileName(fileName);
// set video encoding
((RtspDescribeResponse) rtspResponse).setVideoEncoder(encoder);
// finally set content base
((RtspDescribeResponse)rtspResponse).setContentBase(contentBase);
}
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/Parser.java
================================================
package de.kp.net.rtsp.server.response;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.util.StringTokenizer;
import de.kp.net.rtsp.RtspConstants;
/**
* This class provides a parser for incoming RTSP
* messages and splits them into appropriate parts.
*
* @author Stefan Krusche (krusche@dr-kruscheundpartner.de)
*
*/
public class Parser {
/**
* @param rtspBufferedReader
* @return
* @throws IOException
*/
public static String readRequest(BufferedReader rtspBufferedReader) throws IOException {
String request = new String();
boolean endFound = false;
int c;
while ((c = rtspBufferedReader.read()) != -1) {
request += (char) c;
if (c == '\n') {
if (endFound) {
break;
} else {
endFound = true;
}
} else {
if (c != '\r') {
endFound = false;
}
}
}
return request;
}
/**
* This method determines the request type of an
* incoming RTSP request.
*
* @param request
* @return
*/
public static int getRequestType(String request) {
StringTokenizer tokens = new StringTokenizer(request);
String requestType = "";
if (tokens.hasMoreTokens()) {
requestType = tokens.nextToken();
}
if ((new String(requestType)).compareTo("OPTIONS") == 0)
return RtspConstants.OPTIONS;
else if ((new String(requestType)).compareTo("DESCRIBE") == 0)
return RtspConstants.DESCRIBE;
else if ((new String(requestType)).compareTo("SETUP") == 0)
return RtspConstants.SETUP;
else if ((new String(requestType)).compareTo("PLAY") == 0)
return RtspConstants.PLAY;
else if ((new String(requestType)).compareTo("PAUSE") == 0)
return RtspConstants.PAUSE;
else if ((new String(requestType)).compareTo("TEARDOWN") == 0)
return RtspConstants.TEARDOWN;
return -1;
}
/**
* @param request
* @return
*/
public static String getContentBase(String request) {
StringTokenizer tokens = new StringTokenizer(request);
String contentBase = "";
if (tokens.hasMoreTokens()) {
contentBase = tokens.nextToken();
contentBase = tokens.nextToken();
}
return contentBase;
}
/**
* @param request
* @return
* @throws Exception
*/
public static int getCseq(String request) throws Exception {
String ineInput = getLineInput(request, "\r\n", "CSeq");
String cseq = ineInput.substring(6);
return Integer.parseInt(cseq);
}
/**
* @param request
* @return
* @throws Exception
*/
public static int[] getInterleavedSetup(String request) throws Exception {
int[] interleaved = null;
String lineInput = getLineInput(request, "\r\n", "Transport:");
String[] parts = lineInput.split("interleaved=");
int t = parts.length;
if (t > 1) {
parts = parts[1].split("-");
interleaved = new int[2];
interleaved[0] = Integer.parseInt(parts[0]);
interleaved[1] = Integer.parseInt(parts[1]);
}
return interleaved;
}
/**
* @param request
* @return
* @throws Exception
*/
public static String getFileName(String request) throws Exception {
String lineInput = getLineInput(request, " ", "rtsp");
URI uri = new URI(lineInput);
//String[] parts = lineInput.split("rtsp://" + RtspConstants.SERVER_IP + "/");
//String fileName = parts[1];
String fileName = uri.getPath();
return fileName;
}
/**
* This method retrieves a certain input from an
* incoming RTSP request, described by a separator
* and a specific prefix.
*
* @param request
* @param separator
* @param prefix
* @return
* @throws Exception
*/
public static String getLineInput(String request, String separator, String prefix) throws Exception {
StringTokenizer str = new StringTokenizer(request, separator);
String token = null;
boolean match = false;
while (str.hasMoreTokens()) {
token = str.nextToken();
if (token.startsWith(prefix)) {
match = true;
break;
}
}
return (match == true) ? token : null;
}
/**
* This method retrieves the client port
* from an incoming RTSP request.
*
* @param request
* @return
* @throws Exception
*/
public static int getClientPort(String request) throws Exception {
String lineInput = getLineInput(request, "\r\n", "Transport:");
if (lineInput == null) throw new Exception();
String[] parts = lineInput.split(";");
parts[2] = parts[2].substring(12);
String[] ports = parts[2].split("-");
return Integer.parseInt(ports[0]);
}
/**
* This method retrieves the transport protocol
* from an incoming RTSP request.
*
* @param request
* @return
* @throws Exception
*/
public static String getTransportProtocol(String request) throws Exception {
String lineInput = getLineInput(request, "\r\n", "Transport:");
if (lineInput == null) throw new Exception();
String[] parts = lineInput.split(";");
parts[0] = parts[0].substring(11);
return parts[0];
}
/**
* This method retrieves the range from an
* incoming RTSP request.
*
* @param request
* @return
* @throws Exception
*/
public static String getRangePlay(String request) throws Exception {
String lineInput = getLineInput(request, "\r\n", "Range:");
if (lineInput == null) {
/*
* Android's video view does not provide
* range information with a PLAY request
*/
return null;
}
String[] parts = lineInput.split("=");
return parts[1];
}
/**
*
* This method determines the session type from an
* incoming RTSP request.
*
* @param request
* @return
* @throws Exception
*/
public static String getSessionType(String request) throws Exception {
String lineInput = getLineInput(request, "\r\n", "Transport:");
if (lineInput == null) throw new Exception();
String[] parts = lineInput.split(";");
return parts[1].trim();
}
/**
* This method retrieves the user agent from an
* incoming RTSP request.
*
* @param request
* @return
* @throws Exception
*/
public String getUserAgent(String request) throws Exception{
String lineInput = getLineInput(request, "\r\n", "User-Agent:");
if (lineInput == null) throw new Exception();
String[] parts = lineInput.split(":");
return parts[1];
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspAnnounceResponse.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspAnnounceResponse extends RtspResponse {
public RtspAnnounceResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspDescribeResponse.java
================================================
package de.kp.net.rtsp.server.response;
import java.net.UnknownHostException;
import de.kp.net.rtsp.RtspConstants.VideoEncoder;
public class RtspDescribeResponse extends RtspResponse {
protected String rtpSession = "";
protected String contentBase = "";
private String fileName;
private VideoEncoder encoder;
public RtspDescribeResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
SDP sdp = new SDP(fileName, encoder);
String sdpContent = "";
try {
sdpContent = CRLF2 + sdp.getSdp();
} catch (UnknownHostException e) {
e.printStackTrace();
}
body += "Content-base: "+contentBase + CRLF
+ "Content-Type: application/sdp"+ CRLF
+ "Content-Length: "+ sdpContent.length() + sdpContent;
}
public String getContentBase() {
return contentBase;
}
public void setContentBase(String contentBase) {
this.contentBase = contentBase;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setVideoEncoder(VideoEncoder encoder) {
this.encoder = encoder;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspError.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspError extends RtspResponse {
public RtspError(int cseq) {
super(cseq);
}
protected void generateBody() {
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspOptionsResponse.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspOptionsResponse extends RtspResponse {
public RtspOptionsResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
this.body = "Public:DESCRIBE,SETUP,TEARDOWN,PLAY,PAUSE"/*+SL*/;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspPauseResponse.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspPauseResponse extends RtspResponse {
public RtspPauseResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspPlayResponse.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspPlayResponse extends RtspResponse {
protected String range = "";
public RtspPlayResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
this.body += "Session: " + session_id + CRLF + "Range: npt=" + range;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspResponse.java
================================================
package de.kp.net.rtsp.server.response;
import java.util.Date;
import de.kp.net.rtsp.RtspConstants;
public abstract class RtspResponse {
protected String response="";
protected int cseq = 0;
protected static int session_id = -1;
protected boolean newSessionId = true;
protected String body = "";
/**
* CR =
* LF =
* CRLF = CR LF
*/
public static final String CRLF = "\r\n";
public static final String CRLF2 = "\r\n\r\n";
public static final String SEP = " ";
public RtspResponse(int cseq){
this.cseq = cseq;
}
protected String getHeader() {
StringBuffer sb = new StringBuffer();
sb.append("RTSP/1.0" + SEP + "200" + SEP + "OK" + CRLF);
sb.append(cseq() +CRLF);
sb.append("Date: " + new Date().toGMTString() + CRLF);
sb.append("Server: " + getServer() + CRLF);
return sb.toString();
}
protected String cseq() {
return "CSeq:" + SEP + getCseq();
}
protected String getResponse() {
return response;
}
protected void setResponse(String response) {
this.response = response;
}
protected String getServer(){
return RtspConstants.SERVER_NAME + "/" + RtspConstants.SERVER_VERSION;
}
protected int getCseq() {
return cseq;
}
protected void setCseq(int cseq) {
this.cseq = cseq;
}
protected String getBody() {
return body;
}
protected void setBody(String cuerpo) {
this.body = cuerpo;
}
protected void generate(){
// note that it is important to close the response
// message with 2 CRLFs
response += getHeader();
response += getBody() + CRLF2;
}
protected abstract void generateBody();
public String toString() {
generateBody();
generate();
return response;
}
public void createSessionId(boolean bool){
newSessionId = bool;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspResponseTeardown.java
================================================
package de.kp.net.rtsp.server.response;
public class RtspResponseTeardown extends RtspResponse {
public RtspResponseTeardown(int cseq) {
super(cseq);
}
protected void generar(){
response += getHeader();
response += getBody() + CRLF;
}
protected void generateBody() {
body += "";
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/RtspSetupResponse.java
================================================
package de.kp.net.rtsp.server.response;
import java.util.Random;
import de.kp.net.rtsp.RtspConstants;
public class RtspSetupResponse extends RtspResponse {
private int clientRTP, clientRTCP;
private String clientIP = "";
private int[] interleaved;
private String transportProtocol = "";
private String sessionType = "";
public RtspSetupResponse(int cseq) {
super(cseq);
}
protected void generateBody() {
createSessionId();
body += "Session: " + session_id + CRLF + "Transport: " + transportProtocol + ";" + sessionType + ";";
if (interleaved==null) {
body += "source=" + RtspConstants.SERVER_IP + ";" + getPortPart();
} else {
body += getInterleavedPart();
}
}
private String getPortPart(){
String r= "client_port=" + clientRTP + "-" + clientRTCP + ";" + "server_port=" + RtspConstants.PORTS_RTSP_RTP[0] + "-" + RtspConstants.PORTS_RTSP_RTP[1];
return r;
}
private String getInterleavedPart() {
return "client_ip=" + clientIP + ";interleaved=" + interleaved[0] + "-" + interleaved[1];
}
private final void createSessionId() {
Random r = new Random();
int id = r.nextInt();
if (id < 0) {
id *= -1;
}
if (newSessionId) {
session_id = id;
}
}
public void setClientPort(int port) {
clientRTP = port;
clientRTCP = port + 1;
}
public String getTransportProtocol() {
return transportProtocol;
}
public void setTransportProtocol(String transportProtocol) {
this.transportProtocol = transportProtocol;
}
public String getSessionType() {
return sessionType;
}
public void setSessionType(String sessionType) {
this.sessionType = sessionType;
}
public int[] getInterleaved() {
return interleaved;
}
public void setInterleaved(int[] interleaved) {
this.interleaved = interleaved;
}
public String getClientIP() {
return clientIP;
}
public void setClientIP(String clientIP) {
this.clientIP = clientIP;
}
}
================================================
FILE: RtspCamera/src/de/kp/net/rtsp/server/response/SDP.java
================================================
package de.kp.net.rtsp.server.response;
import java.net.UnknownHostException;
import com.orangelabs.rcs.core.ims.protocol.rtp.codec.video.h264.H264Config;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.RtspConstants.VideoEncoder;
public class SDP {
// the default file name
private String fileName = "kupdroid";
private int audioClientPort = RtspConstants.CLIENT_AUDIO_PORT;
private int clientVideoPort = RtspConstants.CLIENT_VIDEO_PORT;
private VideoEncoder encoder;
public SDP(String fileName, VideoEncoder encoder) {
this.fileName = fileName;
this.encoder = encoder;
}
/**
* This method is used to build a minimal
* SDP file description.
*
* @return
* @throws UnknownHostException
*/
public String getSdp() throws UnknownHostException {
StringBuffer buf = new StringBuffer();
buf.append("v=0" + RtspResponse.CRLF);
// filename contains leading slash
buf.append("s=" + fileName.substring(1) + RtspResponse.CRLF);
int track = 1;
buf.append(getSDPVideo(track));
return buf.toString();
}
/*
private StringBuffer getSDPAudio(){
StringBuffer buf = new StringBuffer();
//m=
buf.append("m=audio " + audioClientPort + " RTP/AVP 14" + RtspResponse.CRLF);
//a=rtpmap: / [/]
buf.append("a=rtpmap:14 MPA/90000" + RtspResponse.CRLF);
buf.append("a=control:rtsp://" + RtspConstants.SERVER_IP + "/audio" + RtspResponse.CRLF);
buf.append("a=mimetype: audio/MPA" + RtspResponse.CRLF);
buf.append("a=range:npt=0-");
return buf;
}
*/
private StringBuffer getSDPVideo(int track){
StringBuffer sb = new StringBuffer();
// H263 encoding
if (encoder.equals(VideoEncoder.H263_ENCODER)) {
// cross encoder properties
sb.append("m=video " + clientVideoPort + RtspConstants.SEP + "RTP/AVP " + RtspConstants.RTP_H263_PAYLOADTYPE + RtspResponse.CRLF);
// set to H263-2000
sb.append("a=rtpmap:" + RtspConstants.RTP_H263_PAYLOADTYPE + RtspConstants.SEP + RtspConstants.H263_2000 + RtspResponse.CRLF);
// additional information for android video view, due to extended checking mechanism
sb.append("a=framesize:" + RtspConstants.RTP_H263_PAYLOADTYPE + RtspConstants.SEP + RtspConstants.WIDTH + "-" + RtspConstants.HEIGHT + RtspResponse.CRLF);
} else if (encoder.equals(VideoEncoder.H264_ENCODER)) {
// cross encoder properties
sb.append("m=video " + clientVideoPort + RtspConstants.SEP + "RTP/AVP " + RtspConstants.RTP_H264_PAYLOADTYPE + RtspResponse.CRLF);
sb.append("a=rtpmap:" + RtspConstants.RTP_H264_PAYLOADTYPE + RtspConstants.SEP + RtspConstants.H264 + RtspResponse.CRLF);
/*
* with change to in-band SPS/PPS parameters following SDP statements should be unnecessary
*/
// 176x144 15fps
//sb.append("a=fmtp:" + RtspConstants.RTP_H264_PAYLOADTYPE + " packetization-mode=0;" + H264Config.CODEC_PARAMS +";sprop-parameter-sets=J0IAINoLExA,KM48gA==;" + RtspResponse.CRLF);
// 352 288 15fps
// sb.append("a=fmtp:" + RtspConstants.RTP_H264_PAYLOADTYPE + " packetization-mode=0;" + H264Config.CODEC_PARAMS +";sprop-parameter-sets=J0IAINoFglE=,KM48gA==;" + RtspResponse.CRLF);
//buf.append("a=fmtp:98 packetization-mode=1;profile-level-id=420020;sprop-parameter-sets=J0IAIKaAoD0Q,KM48gA==;" + RtspResponse.CRLF); // 640x480 20fps
// buf.append("a=fmtp:98 packetization-mode=1;profile-level-id=420020;sprop-parameter-sets=J0IAINoLExA,KM48gA==;" + RtspResponse.CRLF); // 176x144 15fps
// sb.append("a=fmtp:" + RtspConstants.RTP_H264_PAYLOADTYPE + " packetization-mode=1;" + H264Config.CODEC_PARAMS +";sprop-parameter-sets=J0IAIKaCxMQ=,KM48gA==;" + RtspResponse.CRLF); // 176x144 20fps
// buf.append("a=fmtp:98 packetization-mode=1;profile-level-id=420020;sprop-parameter-sets=J0IAINoFB8Q=,KM48gA==;" + RtspResponse.CRLF); // 320x240 10fps
// additional information for android video view, due to extended checking mechanism
sb.append("a=framesize:" + RtspConstants.RTP_H264_PAYLOADTYPE + RtspConstants.SEP + RtspConstants.WIDTH + "-" + RtspConstants.HEIGHT + RtspResponse.CRLF);
}
sb.append("a=control:trackID=" + String.valueOf(track));
return sb;
}
/*
private StringBuffer getSDPWebcam(){
StringBuffer buf = new StringBuffer();
buf.append("m=video " + clientVideoPort + " RTP/AVP 26" + RtspResponse.CRLF);
buf.append("a=rtpmap:26 JPEG/90000"+RtspResponse.CRLF);
buf.append("a=control:rtsp://" + RtspConstants.SERVER_IP + "/video" + RtspResponse.CRLF);
buf.append("a=mimetype: video/JPEG" + RtspResponse.CRLF);
buf.append("a=range:npt=0-100");
return buf;
}
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getClientAudioPort() {
return audioClientPort;
}
public void setClientAudioPort(int clientAudioPort) {
this.audioClientPort = clientAudioPort;
}
public int getClientVideoPort() {
return clientVideoPort ;
}
public void setClientVideoPort(int clientVideoPort) {
this.clientVideoPort = clientVideoPort;
}
}
================================================
FILE: RtspCamera/src/de/kp/rtspcamera/MediaConstants.java
================================================
package de.kp.rtspcamera;
public class MediaConstants {
public static boolean H264_CODEC = true;
}
================================================
FILE: RtspCamera/src/de/kp/rtspcamera/RtspApiCodecsCamera.java
================================================
package de.kp.rtspcamera;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import de.kp.net.rtp.RtpSender;
import de.kp.net.rtp.packetizer.AbstractPacketizer;
import de.kp.net.rtp.packetizer.H263Packetizer;
import de.kp.net.rtp.packetizer.H264Packetizer;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.server.RtspServer;
public class RtspApiCodecsCamera extends Activity {
private String TAG = "RTSPCamera";
// default RTSP command port is 554
private int SERVER_PORT = 8080;
private SurfaceView mVideoPreview;
private SurfaceHolder mSurfaceHolder;
// these parameters are used to separate between incoming
// and outgoing streams
private LocalServerSocket localSocketServer;
private LocalSocket receiver;
private LocalSocket sender;
private MediaRecorder mediaRecorder;
private boolean mediaRecorderRecording = false;
protected boolean videoQualityHigh = false;
private RtpSender rtpSender;
private RtspServer streamer = null;
private AbstractPacketizer videoPacketizer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cameraapicodecs);
// hold the reference
rtpSender = RtpSender.getInstance();
/*
* Video preview initialization
*/
mVideoPreview = (SurfaceView) findViewById(R.id.smallcameraview);
mSurfaceHolder = mVideoPreview.getHolder();
mSurfaceHolder.addCallback(surfaceCallback);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void onResume() {
Log.d(TAG, "onResume");
// starts the RTSP Server
try {
// initialize video encoder to be used
// for SDP file generation
RtspConstants.VideoEncoder rtspVideoEncoder = (MediaConstants.H264_CODEC == true) ? RtspConstants.VideoEncoder.H264_ENCODER
: RtspConstants.VideoEncoder.H263_ENCODER;
if (streamer == null) {
streamer = new RtspServer(SERVER_PORT, rtspVideoEncoder);
new Thread(streamer).start();
}
Log.d(TAG, "RtspServer started");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Camera initialization
*/
receiver = new LocalSocket();
try {
localSocketServer = new LocalServerSocket("camera2rtsp");
// InputStream the RTPPackets can be built from
receiver.connect(new LocalSocketAddress("camera2rtsp"));
receiver.setReceiveBufferSize(500000);
receiver.setSendBufferSize(500000);
// FileDescriptor the Camera can send to
sender = localSocketServer.accept();
sender.setReceiveBufferSize(500000);
sender.setSendBufferSize(500000);
} catch (IOException e1) {
e1.printStackTrace();
super.onResume();
finish();
return;
}
super.onResume();
}
@Override
public void onPause() {
// stop RTSP server
if (streamer != null)
streamer.stop();
streamer = null;
super.onPause();
}
/*
* MediaRecorder listener
*/
private MediaRecorder.OnErrorListener mErrorListener = new MediaRecorder.OnErrorListener() {
public void onError(MediaRecorder mr, int what, int extra) {
// MediaRecorder or MediaPlayer error
rtpSender.stop();
}
};
/*
* SurfaceHolder callback triple
*/
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
/*
* Created state: - Open camera - initial call to startPreview() - hook
* PreviewCallback() on it, which notifies waiting thread with new
* preview data - start thread
*
* @see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.
* SurfaceHolder )
*/
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
}
/*
* Changed state: - initiate camera preview size, set
* camera.setPreviewDisplay(holder) - subsequent call to startPreview()
*
* @see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.
* SurfaceHolder , int, int, int)
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.d(TAG, "surfaceChanged");
initializeVideo();
startVideoRecording();
}
/*
* Destroy State: Take care on release of camera
*
* @see
* android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.
* SurfaceHolder)
*/
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "surfaceDestroyed");
stopVideoRecording();
}
};
// initializeVideo() starts preview and prepare media recorder.
// Returns false if initializeVideo fails
private void initializeVideo() {
Log.d(TAG, "initializeVideo: " + mediaRecorderRecording);
mediaRecorderRecording = true;
Log.v(TAG, "initializeVideo set to true: " + mediaRecorderRecording);
if (mediaRecorder == null)
mediaRecorder = new MediaRecorder();
else
mediaRecorder.reset();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// route video to LocalSocket
mediaRecorder.setOutputFile(sender.getFileDescriptor());
// Use the same frame rate for both, since internally
// if the frame rate is too large, it can cause camera to become
// unstable. We need to fix the MediaRecorder to disable the support
// of setting frame rate for now.
mediaRecorder.setVideoFrameRate(RtspConstants.FPS);
// mMediaRecorder.setVideoEncodingBitRate(RtspConstants.BITRATE);
mediaRecorder.setVideoSize(Integer.valueOf(RtspConstants.WIDTH), Integer.valueOf(RtspConstants.HEIGHT));
mediaRecorder.setVideoEncoder(getMediaEncoder());
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
try {
mediaRecorder.prepare();
mediaRecorder.setOnErrorListener(mErrorListener);
mediaRecorder.start();
} catch (IOException exception) {
exception.printStackTrace();
releaseMediaRecorder();
}
}
private int getMediaEncoder() {
if (MediaConstants.H264_CODEC == true)
return MediaRecorder.VideoEncoder.H264;
return MediaRecorder.VideoEncoder.H263;
}
private void startVideoRecording() {
Log.v(TAG, "startVideoRecording");
InputStream fis = null;
try {
fis = receiver.getInputStream();
} catch (IOException e1) {
Log.w(TAG, "No receiver input stream");
return;
}
try {
// actually H263 over RTP and H264 over RTP is supported
if (MediaConstants.H264_CODEC == true) {
videoPacketizer = new H264Packetizer(fis);
} else {
videoPacketizer = new H263Packetizer(fis);
}
videoPacketizer.startStreaming();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void stopVideoRecording() {
Log.d(TAG, "stopVideoRecording");
if (mediaRecorderRecording || mediaRecorder != null) {
try {
// stop thread
videoPacketizer.stopStreaming();
if (mediaRecorderRecording && mediaRecorder != null) {
try {
mediaRecorder.setOnErrorListener(null);
mediaRecorder.setOnInfoListener(null);
mediaRecorder.stop();
} catch (RuntimeException e) {
Log.e(TAG, "stop fail: " + e.getMessage());
}
mediaRecorderRecording = false;
}
} catch (Exception e) {
Log.e(TAG, "stopVideoRecording failed");
e.printStackTrace();
} finally {
releaseMediaRecorder();
}
}
}
private void releaseMediaRecorder() {
Log.d(TAG, "Releasing media recorder.");
if (mediaRecorder != null) {
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
}
}
}
================================================
FILE: RtspCamera/src/de/kp/rtspcamera/RtspNativeCodecsCamera.java
================================================
package de.kp.rtspcamera;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import de.kp.net.rtp.recorder.RtspVideoRecorder;
import de.kp.net.rtsp.RtspConstants;
import de.kp.net.rtsp.server.RtspServer;
public class RtspNativeCodecsCamera extends Activity {
private String TAG = "RTSPNativeCamera";
// default RTSP command port is 554
// private int SERVER_PORT = 8080;
private RtspVideoRecorder outgoingPlayer;
private SurfaceView mCameraPreview;
private SurfaceHolder previewHolder;
private Camera camera;
private boolean inPreview = false;
private boolean cameraConfigured = false;
private int mPreviewWidth = Integer.valueOf(RtspConstants.WIDTH);
private int mPreviewHeight = Integer.valueOf(RtspConstants.HEIGHT);
private RtspServer streamer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cameranativecodecs);
/*
* Camera preview initialization
*/
mCameraPreview = (SurfaceView) findViewById(R.id.smallcameraview);
previewHolder = mCameraPreview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// outgoingPlayer = new RtspVideoRecorder("h263-2000");
outgoingPlayer = new RtspVideoRecorder("h264");
outgoingPlayer.open();
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
// starts the RTSP Server
try {
// initialize video encoder to be used
// for SDP file generation
RtspConstants.VideoEncoder rtspVideoEncoder = (MediaConstants.H264_CODEC == true) ? RtspConstants.VideoEncoder.H264_ENCODER
: RtspConstants.VideoEncoder.H263_ENCODER;
if (streamer == null) {
streamer = new RtspServer(RtspConstants.SERVER_PORT, rtspVideoEncoder);
new Thread(streamer).start();
}
Log.d(TAG, "RtspServer started");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Camera initialization
*/
camera = Camera.open();
super.onResume();
}
@Override
public void onPause() {
// stop RTSP server
if (streamer != null)
streamer.stop();
streamer = null;
super.onPause();
}
/*
* SurfaceHolder callback triple
*/
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
/*
* Created state: - Open camera - initial call to startPreview() - hook
* PreviewCallback() on it, which notifies waiting thread with new
* preview data - start thread
*
* @see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.
* SurfaceHolder )
*/
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
}
/*
* Changed state: - initiate camera preview size, set
* camera.setPreviewDisplay(holder) - subsequent call to startPreview()
*
* @see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.
* SurfaceHolder , int, int, int)
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.d(TAG, "surfaceChanged");
initializePreview(w, h);
startPreview();
}
/*
* Destroy State: Take care on release of camera
*
* @see
* android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.
* SurfaceHolder)
*/
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "surfaceDestroyed");
if (inPreview) {
camera.stopPreview();
}
camera.setPreviewCallback(null);
camera.release();
camera = null;
// stop captureThread
outgoingPlayer.stop();
inPreview = false;
cameraConfigured = false;
}
};
/**
* This method checks availability of camera and preview
*
* @param width
* @param height
*/
private void initializePreview(int width, int height) {
Log.d(TAG, "initializePreview");
if (camera != null && previewHolder.getSurface() != null) {
try {
// provide SurfaceView for camera preview
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e(TAG, "Exception in setPreviewDisplay()", t);
}
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
private void startPreview() {
Log.d(TAG, "startPreview");
if (cameraConfigured && camera != null) {
// activate onPreviewFrame()
// camera.setPreviewCallback(cameraPreviewCallback);
camera.setPreviewCallback(outgoingPlayer);
// start captureThread
outgoingPlayer.start();
camera.startPreview();
inPreview = true;
}
}
public boolean isReady() {
return this.inPreview;
}
}
================================================
FILE: RtspViewer/.classpath
================================================
================================================
FILE: RtspViewer/.gitignore
================================================
/bin
/gen
================================================
FILE: RtspViewer/.project
================================================
RtspViewer
com.android.ide.eclipse.adt.ResourceManagerBuilder
com.android.ide.eclipse.adt.PreCompilerBuilder
org.eclipse.jdt.core.javabuilder
com.android.ide.eclipse.adt.ApkBuilder
com.android.ide.eclipse.adt.AndroidNature
org.eclipse.jdt.core.javanature
================================================
FILE: RtspViewer/AndroidManifest.xml
================================================
================================================
FILE: RtspViewer/gpl.txt
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: RtspViewer/proguard-project.txt
================================================
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: RtspViewer/project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}\tools\proguard\proguard-android.txt:proguard-project.txt
# Project target.
target=android-10
android.library.reference.1=../RtspCamera
================================================
FILE: RtspViewer/res/layout/videoview.xml
================================================
================================================
FILE: RtspViewer/res/values/strings.xml
================================================
Hello World, RtspViewerActivity!
RtspViewer
================================================
FILE: RtspViewer/src/de/kp/rtspviewer/RtspViewerActivity.java
================================================
package de.kp.rtspviewer;
/**
* This is the most minimal viewer for RtspCamera app
*
* @author Peter Arwanitis (arwanitis@dr-kruscheundpartner.de)
*
*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.orangelabs.rcs.platform.AndroidFactory;
import com.orangelabs.rcs.provider.settings.RcsSettings;
import com.orangelabs.rcs.service.api.client.media.video.VideoSurfaceView;
import de.kp.net.rtp.viewer.RtpVideoRenderer;
public class RtspViewerActivity extends Activity {
/**
* Video renderer
*/
private RtpVideoRenderer incomingRenderer = null;
/**
* Video preview
*/
private VideoSurfaceView incomingVideoView = null;
/**
* hardcoded rtsp server path
*/
private String rtspConnect = "rtsp://192.168.178.47:8080/video";
// private String rtsp =
// "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov";
private int videoHeight;
private int videoWidth;
private String TAG = "RtspViewer";
@Override
public void onCreate(Bundle icicle) {
Log.i(TAG, "onCreate");
super.onCreate(icicle);
// Set application context ... skipping FileFactory
AndroidFactory.setApplicationContext(getApplicationContext());
// Instantiate the settings manager
RcsSettings.createInstance(getApplicationContext());
setContentView(R.layout.videoview);
// h263-2000
//
// - h263-2000
// - h264
//
//
// - Low (H.263)
// - High (H.264)
//
//
// QCIF
//
// - QCIF
//
//
//
// - Low (176x144)
//
//
// Set incoming video preview
if (incomingVideoView == null) {
incomingVideoView = (VideoSurfaceView) findViewById(R.id.incoming_video_view);
incomingVideoView.setAspectRatio(videoWidth, videoHeight);
try {
incomingRenderer = new RtpVideoRenderer(rtspConnect);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
incomingRenderer.setVideoSurface(incomingVideoView);
}
}
@Override
protected void onPause() {
Log.i(TAG, "onPause");
super.onPause();
}
@Override
protected void onResume() {
Log.i(TAG, "onResume");
super.onResume();
incomingRenderer.open();
incomingRenderer.start();
Log.i(TAG, "onResume renderer started");
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
super.onDestroy();
incomingRenderer.stop();
incomingRenderer.close();
}
}