#30 - WIP on the shoutcast v2 protocol

This commit is contained in:
Denny
2016-09-14 06:07:21 -04:00
parent 2537a71375
commit 6138838d60
18 changed files with 302 additions and 39 deletions

View File

@@ -0,0 +1,145 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v1;
import audio.broadcast.BroadcastConfiguration;
import audio.broadcast.BroadcastFormat;
import audio.broadcast.BroadcastServerType;
public class ShoutcastV1Configuration extends BroadcastConfiguration
{
private String mStreamName;
private String mGenre;
private boolean mPublic;
private int mChannels;
private int mBitRate;
private String mURL;
public ShoutcastV1Configuration(BroadcastFormat format)
{
super(format);
}
@Override
public BroadcastServerType getBroadcastServerType()
{
return BroadcastServerType.SHOUTCAST_V1;
}
/**
* Stream name
*/
public String getStreamName()
{
return mStreamName;
}
/**
* Sets the stream name
* @param name
*/
public void setStreamName(String name)
{
mStreamName = name;
}
/**
* Stream genre
*/
public String getGenre()
{
return mGenre;
}
/**
* Stream genre
* @param genre
*/
public void setGenre(String genre)
{
mGenre = genre;
}
/**
* Public visibility of the broadcast
*/
public boolean isPublic()
{
return mPublic;
}
/**
* Sets public visibility of the broadcast
* @param isPublic indicates if the broadcast should be visible to the public
*/
public void setPublic(boolean isPublic)
{
mPublic = isPublic;
}
/**
* Number of audio channels in the broadcast
*/
public int getChannels()
{
return mChannels;
}
/**
* Sets the number of audio channels in the broadcast
*/
public void setChannels(int channels)
{
mChannels = channels;
}
/**
* Bit rate in bits per second
*/
public int getBitRate()
{
return mBitRate;
}
/**
* Bit rate
* @param bitRate in samples per second
*/
public void setBitRate(int bitRate)
{
mBitRate = bitRate;
}
/**
* URL associated with the broadcast where users can find additional details.
*/
public String getURL()
{
return mURL;
}
/**
* URL associated with the broadcast where users can find additional details.
* @param url
*/
public void setURL(String url)
{
mURL = url;
}
}

View File

@@ -0,0 +1,380 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v1;
import audio.AudioPacket;
import audio.broadcast.Broadcaster;
import audio.broadcast.BroadcasterFactory;
import audio.broadcast.BroadcastFormat;
import audio.broadcast.BroadcastMetadata;
import audio.broadcast.BroadcastHandler;
import audio.broadcast.BroadcastState;
import audio.convert.IAudioConverter;
import controller.ThreadPoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import record.wave.AudioPacketMonoWaveReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ShoutcastV1Handler extends BroadcastHandler
{
private final static Logger mLog = LoggerFactory.getLogger( ShoutcastV1Handler.class );
private static final long RECONNECT_INTERVAL_MILLISECONDS = 15000; //15 seconds
private long mLastConnectionAttempt = 0;
private Socket mSocket;
private DataOutputStream mOutputStream;
private DataInputStream mInputStream;
private static final int mBufferSize = 2000;
/**
* Creates a Shoutcast Version 1 broadcast handler.
* @param configuration
* @param audioConverter
*/
public ShoutcastV1Handler(ShoutcastV1Configuration configuration, IAudioConverter audioConverter)
{
super(configuration, audioConverter);
}
/**
* Shoutcast V1 Configuration information
*/
private ShoutcastV1Configuration getShoutcastConfiguration()
{
return (ShoutcastV1Configuration)getBroadcastConfiguration();
}
/**
* Process audio packets using Shoutcast V1 Protocol
* @param audioPackets
*/
@Override
public void broadcast(List<AudioPacket> audioPackets)
{
//If we're connected, send the audio, otherwise discard it
if(connect())
{
byte[] convertedAudio = mAudioConverter.convert(audioPackets);
if(convertedAudio != null)
{
try
{
send(convertedAudio);
}
catch(IOException e)
{
mLog.error("Error while dispatching audio", e);
setBroadcastState(BroadcastState.BROADCAST_ERROR);
}
}
}
}
/**
* Indicates if the audio handler is currently connected to the remote server and capable of streaming audio.
*
* This method will attempt to establish a connection or reconnect to the streaming server.
* @return true if the audio handler can stream audio
*/
private boolean connect()
{
if(!connected())
{
createConnection();
}
return connected();
}
/**
* Disconnect from the remote server
*/
@Override
public void disconnect()
{
}
/**
* Creates a connnection to the remote server using the shoutcast configuration information. Once disconnected
* following a successful connection, attempts to reestablish a connection on a set interval
*/
private void createConnection()
{
if(!connected() && System.currentTimeMillis() - mLastConnectionAttempt >= RECONNECT_INTERVAL_MILLISECONDS)
{
createSocket();
if(mSocket.isConnected())
{
mLog.debug("Sending credentials");
StringBuilder sb = new StringBuilder();
//Password
sb.append(getShoutcastConfiguration().getPassword()).append(BroadcastMetadata.COMMAND_TERMINATOR);
//Metadata
sb.append(BroadcastMetadata.STREAM_NAME.encode(getShoutcastConfiguration().getStreamName()));
sb.append(BroadcastMetadata.URL.encode(getShoutcastConfiguration().getURL()));
sb.append(BroadcastMetadata.PUBLIC.encode(getShoutcastConfiguration().isPublic()));
sb.append(BroadcastMetadata.GENRE.encode(getShoutcastConfiguration().getGenre()));
sb.append(BroadcastMetadata.AUDIO_BIT_RATE.encode(getShoutcastConfiguration().getBitRate()));
//End of connection string
sb.append(BroadcastMetadata.COMMAND_TERMINATOR);
try
{
send(sb.toString());
if(isInvalidResponse())
{
mLog.error("Invalid response after sending metadata");
return;
}
else
{
setBroadcastState(BroadcastState.CONNECTED);
}
}
catch(IOException ioe)
{
mLog.debug("Error while connecting to server", ioe);
setBroadcastState(BroadcastState.ERROR);
}
mLog.debug("Connection established");
}
}
}
/**
* Sends the string data to the remote server
* @param data to send
* @throws IOException if there is an error communicating with the remote server
*/
private void send(String data) throws IOException
{
mLog.debug("Sending [" + data + "]");
if(data != null && !data.isEmpty() && mOutputStream != null)
{
mOutputStream.writeBytes(data);
}
}
/**
* Sends the byte data to the remote server
* @param data to send
* @throws IOException if there is an error communicating with the remote server
*/
private void send(byte[] data) throws IOException
{
mLog.debug("Sending bytes:" + data.length);
if(connected())
{
int sent = 0;
while(sent < data.length)
{
int available = data.length - sent;
int sending = available <mBufferSize ? available : mBufferSize;
mOutputStream.write(data, sent, sending);
sent += sending;
}
}
}
private String getResponse() throws IOException
{
if(mInputStream != null)
{
int bytesAvailable = mInputStream.available();
if(bytesAvailable > 0)
{
byte[] responseBuffer = new byte[bytesAvailable];
int bytesRead = 0;
while(bytesRead < bytesAvailable)
{
bytesRead += mInputStream.read(responseBuffer, bytesRead, bytesAvailable - bytesRead);
}
return new String(responseBuffer);
}
}
return null;
}
private boolean isInvalidResponse()
{
String response;
try
{
response = getResponse();
}
catch(IOException e)
{
mLog.error("Error while retrieving server response message", e);
setBroadcastState(BroadcastState.ERROR);
return false;
}
if(response != null && !response.isEmpty())
{
if(response.startsWith("OK"))
{
return false;
}
else if(response.startsWith("Invalid Password"))
{
setBroadcastState(BroadcastState.INVALID_PASSWORD);
return true;
}
mLog.debug("Unrecognized server response:" + response);
return true;
}
return false;
}
/**
* Creates a socket connection to the remote server and sets the state to CONNECTING.
*/
private void createSocket()
{
if(mSocket == null)
{
mLog.debug("Creating socket");
try
{
mSocket = new Socket(getShoutcastConfiguration().getHost(),
getShoutcastConfiguration().getPort());
mOutputStream = new DataOutputStream(mSocket.getOutputStream());
mInputStream = new DataInputStream(mSocket.getInputStream());
}
catch(UnknownHostException uhe)
{
setBroadcastState(BroadcastState.UNKNOWN_HOST);
mLog.error("Unknown host or port. Unable to create connection to streaming server host[" +
getShoutcastConfiguration().getHost() + "] and port[" +
getShoutcastConfiguration().getPort() + "] - will reattempt connection periodically");
return;
}
catch(IOException ioe)
{
setBroadcastState(BroadcastState.ERROR);
mLog.error("Error connecting to streaming server host[" +
getShoutcastConfiguration().getHost() + "] and port[" +
getShoutcastConfiguration().getPort() + "]", ioe);
return;
}
}
if(mSocket.isConnected())
{
setBroadcastState(BroadcastState.CONNECTING);
}
else
{
try
{
SocketAddress address = getShoutcastConfiguration().getAddress();
mSocket.connect(address);
setBroadcastState(BroadcastState.CONNECTING);
}
catch(UnknownHostException uhe)
{
setBroadcastState(BroadcastState.UNKNOWN_HOST);
}
catch(IOException e)
{
setBroadcastState(BroadcastState.ERROR);
mLog.error("Error connecting to streaming server host[" +
getShoutcastConfiguration().getHost() + "] and port[" +
getShoutcastConfiguration().getPort() + "]", e);
}
}
}
public static void main(String[] args)
{
ShoutcastV1Configuration config = new ShoutcastV1Configuration(BroadcastFormat.MP3);
config.setAlias("Test Configuration");
config.setHost("localhost");
config.setPort(8000);
config.setPassword("denny3");
config.setStreamName("Denny's Audio Broadcast Test");
config.setGenre("Scanner Audio");
config.setPublic(true);
config.setURL("http://localhost:8000");
config.setBitRate(16);
ThreadPoolManager threadPoolManager = new ThreadPoolManager();
final Broadcaster broadcaster = BroadcasterFactory.getBroadcaster(threadPoolManager,config);
Path path = Paths.get("/home/denny/Music/PCM.wav");
mLog.debug("Opening: " + path.toString());
mLog.debug("Registering and starting audio playback");
while(true)
{
mLog.debug("Playback started [" + path.toString() + "]");
try (AudioPacketMonoWaveReader reader = new AudioPacketMonoWaveReader(path, true))
{
reader.setListener(broadcaster);
reader.read();
}
catch (IOException e)
{
mLog.error("Error", e);
}
mLog.debug("Playback ended [" + path.toString() + "]");
}
}
}

View File

@@ -0,0 +1,183 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v2;
import audio.broadcast.BroadcastConfiguration;
import audio.broadcast.BroadcastFormat;
import audio.broadcast.BroadcastServerType;
public class ShoutcastV2Configuration extends BroadcastConfiguration
{
private String mMountPoint;
private String mStreamName;
private String mSongTitle;
private String mGenre;
private boolean mPublic;
private int mChannels;
private int mBitRate;
private String mURL;
public ShoutcastV2Configuration(BroadcastFormat format)
{
super(format);
}
@Override
public BroadcastServerType getBroadcastServerType()
{
return BroadcastServerType.SHOUTCAST_V1;
}
public String getMountPoint()
{
return mMountPoint;
}
/**
* Sets the optional mount point. Shoutcast v1.x servers don't require a mount point, but v2.x servers do require
* the mount point.
*
* Note: if the supplied mount point contains a leading slash (/) it will be removed.
*
* @param mountPoint
*/
public void setMountPoint(String mountPoint)
{
//Strip the leading slash from the mount point if the user supplies it
mMountPoint = mountPoint.replace("/", "");
}
/**
* Stream name
*/
public String getStreamName()
{
return mStreamName;
}
/**
* Sets the stream name
* @param name
*/
public void setStreamName(String name)
{
mStreamName = name;
}
/**
* Song title
*/
public String getSongTitle()
{
return mSongTitle;
}
/**
* Set the song title
*/
public void setSongTitle(String title)
{
mSongTitle = title;
}
/**
* Stream genre
*/
public String getGenre()
{
return mGenre;
}
/**
* Stream genre
* @param genre
*/
public void setGenre(String genre)
{
mGenre = genre;
}
/**
* Public visibility of the broadcast
*/
public boolean isPublic()
{
return mPublic;
}
/**
* Sets public visibility of the broadcast
* @param isPublic indicates if the broadcast should be visible to the public
*/
public void setPublic(boolean isPublic)
{
mPublic = isPublic;
}
/**
* Number of audio channels in the broadcast
*/
public int getChannels()
{
return mChannels;
}
/**
* Sets the number of audio channels in the broadcast
*/
public void setChannels(int channels)
{
mChannels = channels;
}
/**
* Bit rate in bits per second
*/
public int getBitRate()
{
return mBitRate;
}
/**
* Bit rate
* @param bitRate in samples per second
*/
public void setBitRate(int bitRate)
{
mBitRate = bitRate;
}
/**
* URL associated with the broadcast where users can find additional details.
*/
public String getURL()
{
return mURL;
}
/**
* URL associated with the broadcast where users can find additional details.
* @param url
*/
public void setURL(String url)
{
mURL = url;
}
}

View File

@@ -0,0 +1,157 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v2;
import bits.BinaryMessage;
import com.sun.org.apache.regexp.internal.RE;
public abstract class UltravoxMessage
{
public static final int[] SYNC = {0,1,2,3,4,5,6,7};
public static final int[] RESERVED = {8,9,10,11};
public static final int REQUIRED_DELIVERY = 12;
public static final int[] SEND_QUEUE_PRIORITY = {13,14,15};
public static final int[] MESSAGE_CLASS = {16,17,18,19};
public static final int[] MESSAGE_CLASS_AND_TYPE = {16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
public static final int[] PAYLOAD_LENGTH = {32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47};
private BinaryMessage mMessage;
/**
* Constructs a message from the byte array
*/
public UltravoxMessage(byte[] data)
{
mMessage = new BinaryMessage(data);
}
/**
* Constructs an empty message of the specified length
*
* @param ultravoxMessageType type of message
* @param length of message in bits (64 minimum)
*/
public UltravoxMessage(UltravoxMessageType ultravoxMessageType, int length)
{
assert(length >= 64);
mMessage = new BinaryMessage(length);
setSync();
setMessageType(ultravoxMessageType);
}
/**
* Sets the message sync bits to the predefined sync pattern: 01011010 (0x5A)
*/
private void setSync()
{
mMessage.setInt(0x5A, SYNC);
}
/**
* Ultravox message class
*/
public UltravoxMessageClass getMessageClass()
{
return UltravoxMessageClass.fromValue(mMessage.getInt(MESSAGE_CLASS));
}
/**
* Ultravox message type
* @return
*/
public UltravoxMessageType getMessageType()
{
return UltravoxMessageType.fromValue(mMessage.getInt(MESSAGE_CLASS_AND_TYPE));
}
/**
* Sets the message bits according to the message class and type
* @param messageType of ultravox message
*/
private void setMessageType(UltravoxMessageType messageType)
{
mMessage.setInt(messageType.getValue(), MESSAGE_CLASS_AND_TYPE);
}
/**
* Indicates if this message has the required delivery flag set
*/
public boolean isRequiredDelivery()
{
return mMessage.get(REQUIRED_DELIVERY);
}
/**
* Sets the required delivery flag according to the argument
*/
public void setRequiredDelivery(boolean required)
{
if(required)
{
mMessage.set(REQUIRED_DELIVERY);
}
else
{
mMessage.clear(REQUIRED_DELIVERY);
}
}
/**
* Send queue priority (0 - 7) for this message
*/
public int getSendQueuePriority()
{
return mMessage.getInt(SEND_QUEUE_PRIORITY);
}
/**
* Sets send queue priority for this message
* @param priority 0 - 7
*/
public void setSendQueuePriority(int priority)
{
assert(0 <= priority && priority <= 7);
mMessage.setInt(priority, SEND_QUEUE_PRIORITY);
}
/**
* Message payload
*/
public String getPayload()
{
//TODO: parse payload field
return null;
}
/**
* Sets the message payload, updates the message length field, and appends a trailing 0x00 byte after the payload.
*/
public void setPayload(String payload)
{
//TODO: implement payload, along with trailing 0x00 byte and update overall payload size field.
}
private void setPayloadLength(int length)
{
//TODO: correctly size the message to payload + 1 byte and set the payload length field
}
}

View File

@@ -0,0 +1,57 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v2;
public enum UltravoxMessageClass
{
OPERATIONS(0x0),
BROADCASTER(0x1),
LISTENER(0x2),
CACHEABLE_METADATA_1(0x3),
CACHEABLE_METADATA_2(0x4),
PASS_THROUGH_METADATA_1(0x5),
PASS_THROUGH_METADATA_2(0x6),
ENCODED_DATA(0x7),
ADVANCED_ENCODED_DATA(0x8),
FRAMED_DATA(0x9),
CACHEABLE_BINARY_METADATA(0xA),
UNKNOWN(0xF);
private int mValue;
private UltravoxMessageClass(int value)
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public static UltravoxMessageClass fromValue(int value)
{
if(0x0 <= value && value <= 0xA)
{
return values()[value];
}
return UNKNOWN;
}
}

View File

@@ -0,0 +1,49 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer
*
* 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 <http://www.gnu.org/licenses/>
*
******************************************************************************/
package audio.broadcast.shoutcast.v2;
public enum UltravoxMessageType
{
AUTHENTICATE_BROADCAST(0x1001),
UNKNOWN(0x0000);
private int mValue;
private UltravoxMessageType(int value)
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public static UltravoxMessageType fromValue(int value)
{
switch(value)
{
case 0x1001:
return AUTHENTICATE_BROADCAST;
default:
return UNKNOWN;
}
}
}