I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
Jon Kittel provided a good answer, anyway in the question comments it is mentioned UNICAST communication, so Jon's code is not usable in this case. A simplified unicast receiver is provided below (credit to P. Tellenbach for the original example).
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class DatagramServer
{
private final static int PACKETSIZE = 2048 ;
public static void main( String args[] )
{
// Check the arguments
// if( args.length != 1 )
// {
// System.out.println( "usage: DatagramServer port" ) ;
// return ;
// }
try
{
// Convert the argument to ensure that is it valid
int port = 1234; //Integer.parseInt( args[0] ) ;
FileOutputStream output = new FileOutputStream("testStream.ts", true);
// Construct the socket
DatagramSocket socket = new DatagramSocket( port ) ;
System.out.println( "The server is ready..." ) ;
DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ;
for( ;; )
{
// Receive a packet (blocking)
socket.receive( packet );
try {
output.write(packet.getData());
} finally {
output.close();
}
}
}catch (IOException exception) {
exception.printStackTrace();
}
}
}
This client will listen for UDP stream on localhost address, port 1234, and will write each received packet into testStream.ts file. If the stream is H.264 encoded Mpeg-ts, the outputfile can be opened in any moment with a player to reproduce the video stream captured until that moment.