#30 WIP - broadcastify and icecast TCP streams working and editors are complete. Adds icons to editor and table views.

This commit is contained in:
Denny
2016-12-04 07:28:03 -05:00
parent b71415b82a
commit f44892c62b
22 changed files with 1189 additions and 889 deletions

View File

@@ -18,29 +18,19 @@
******************************************************************************/
package audio.broadcast.icecast;
import alias.Alias;
import alias.id.broadcast.BroadcastChannel;
import audio.AudioPacket;
import audio.broadcast.AudioBroadcaster;
import audio.broadcast.BroadcastFactory;
import audio.broadcast.BroadcastFormat;
import audio.broadcast.BroadcastState;
import audio.metadata.AudioMetadata;
import audio.metadata.Metadata;
import audio.metadata.MetadataType;
import controller.ThreadPoolManager;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Response;
import org.asynchttpclient.uri.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import record.wave.AudioPacketMonoWaveReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -51,8 +41,6 @@ import java.net.SocketAddress;
import java.net.SocketException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
@@ -90,7 +78,7 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
/**
* Configuration information
* Icecast broadcast configuration
*/
private IcecastTCPConfiguration getConfiguration()
{
@@ -98,7 +86,7 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
/**
* Broadcast any queued audio packets using Icecast V2 Protocol
* Broadcasts the audio frame or sequence
*/
@Override
protected void broadcastAudio(byte[] audio)
@@ -117,10 +105,10 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
catch(SocketException se)
{
//The remote server likely disconnected - setup to reconnect
mLog.error("Socket Exception on Icecast TCP Audio Broadcaster -- disconnecting and resetting", se);
disconnect(false);
mLog.error("Resetting Icecast TCP Audio Broadcaster - socket error: " + se.getMessage());
disconnect();
}
catch(IOException e)
catch(Exception e)
{
completed = true;
mLog.error("Error sending audio", e);
@@ -133,6 +121,9 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
}
/**
* Broadcasts an audio metadata update
*/
@Override
protected void broadcastMetadata(AudioMetadata metadata)
{
@@ -214,16 +205,7 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
builder.setRealm(realm);
builder.addHeader(IcecastHeader.USER_AGENT.getValue(), SystemProperties.getInstance().getApplicationName());
AsyncHandler handler = new AsyncCompletionHandler()
{
@Override
public Object onCompleted(Response response) throws Exception
{
return null;
}
};
mDefaultAsyncHttpClient.executeRequest(builder.build(), handler);
mDefaultAsyncHttpClient.executeRequest(builder.build());
}
catch(Exception e)
{
@@ -237,9 +219,11 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
/**
* Indicates if the audio handler is currently connected to the remote server and capable of streaming audio.
* (Re)Connects the broadcaster to the remote server if it currently is disconnected and indicates if the broadcaster
* is currently connected to the remote server following any connection attempts.
*
* Attempts to connect via this method when the broadcast state indicates an error condition will be ignored.
*
* 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()
@@ -254,10 +238,12 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
/**
* Disconnect from the remote server
* Disconnect from the remote broadcast server and cleanup input/output streams and socket connection
*/
public void disconnect(boolean shutdown)
public void disconnect()
{
mLog.info("Disconnecting Icecast TCP audio broadcaster");
if(mOutputStream != null)
{
try
@@ -301,19 +287,16 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
mSocket = null;
}
if(shutdown)
{
setBroadcastState(BroadcastState.DISCONNECTED);
}
else
if(!isErrorState())
{
setBroadcastState(BroadcastState.READY);
}
}
/**
* 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
* Creates a connection to the remote server using the icecast configuration information. Once disconnected
* following a successful connection, successive calls to this method will attempt to reestablish a connection on a
* minimum reconnection attempt interval
*/
private void createConnection()
{
@@ -340,12 +323,6 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
sb.append(IcecastHeader.PUBLIC.getValue()).append(SEPARATOR)
.append(getConfiguration().isPublic() ? "1" : "0").append(TERMINATOR);
if(getConfiguration().hasName())
{
sb.append(IcecastHeader.NAME.getValue()).append(SEPARATOR)
.append(getConfiguration().getName()).append(TERMINATOR);
}
if(getConfiguration().hasGenre())
{
sb.append(IcecastHeader.GENRE.getValue()).append(SEPARATOR)
@@ -374,13 +351,17 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
mLog.debug("Checking response ...");
checkResponse();
checkConnectionAttemptResponse();
}
mConnecting.set(false);
}
}
/**
* Creates an audio metadata description string that can optionally be included when connecting to the remote
* broadcast server.
*/
private String getAudioInfoMetadata()
{
StringBuilder sb = new StringBuilder();
@@ -422,13 +403,13 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
/**
* Creates a socket connection to the remote server and sets the state to CONNECTING.
* Creates a socket connection to the remote server and sets the state to CONNECTING or indicates an error state
* if the socket is unable to connect to the remote server with the current configuration information.
*/
private void createSocket()
{
if(mSocket == null)
{
mLog.debug("Creating socket");
try
{
mSocket = new Socket(getConfiguration().getHost(),
@@ -492,6 +473,7 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
/**
* Sends the string data to the remote server
*
* @param data to send
* @throws IOException if there is an error communicating with the remote server
*/
@@ -525,6 +507,11 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
}
}
/**
* Obtains any pending response from the remote server.
* @return string response
* @throws IOException if there is an error
*/
private String getResponse() throws IOException
{
if(mInputStream != null)
@@ -549,7 +536,11 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
return null;
}
private void checkResponse()
/**
* Checks for a remote server response following a connection attempt and evaluates the response for indication of a
* successful connection or an error state
*/
private void checkConnectionAttemptResponse()
{
String response = null;
@@ -575,86 +566,23 @@ public class IcecastTCPAudioBroadcaster extends AudioBroadcaster
{
setBroadcastState(BroadcastState.CONNECTED);
}
else if(response.startsWith("HTTP/1.0 403 Mountpoint in use"))
{
setBroadcastState(BroadcastState.MOUNT_POINT_IN_USE);
}
else if(response.contains("Invalid Password") || response.contains("Authentication Required"))
{
setBroadcastState(BroadcastState.INVALID_PASSWORD);
}
else
{
mLog.debug("Unrecognized server response:" + response);
mLog.error("Unrecognized server response:" + response);
setBroadcastState(BroadcastState.ERROR);
}
}
else
{
setBroadcastState(BroadcastState.CONNECTED);
mLog.debug("Response was empty");
}
}
public static void main(String[] args)
{
boolean test = false;
IcecastTCPConfiguration config = new IcecastTCPConfiguration(BroadcastFormat.MP3);
String streamName = "Broadcastify SDRTrunk #2";
config.setName(streamName);
config.setHost("audio3.broadcastify.com");
config.setPort(80);
config.setMountPoint("/k0yrdpx7zn4h");
config.setUserName("source");
config.setPassword("k8j9405n");
config.setDescription("SDRTrunk Test Feed #2");
config.setGenre("Scanner");
config.setPublic(false);
config.setURL("http://www.radioreference.com");
config.setBitRate(16);
AudioMetadata metadata = new AudioMetadata(0, false);
Alias toAlias = new Alias("ToAlias");
toAlias.addAliasID(new BroadcastChannel(streamName));
metadata.receive(new Metadata(MetadataType.TO, "1234", toAlias ));
if(test)
{
mLog.debug("Auth:" + config.getEncodedCredentials());
}
else
{
ThreadPoolManager threadPoolManager = new ThreadPoolManager();
DefaultAsyncHttpClient httpClient = new DefaultAsyncHttpClient();
final AudioBroadcaster audioBroadcaster = BroadcastFactory.getBroadcaster(httpClient, threadPoolManager,config);
Path path = Paths.get("/home/denny/Music/PCM.wav");
mLog.debug("Opening: " + path.toString());
mLog.debug("Registering and starting audio playback");
int playCount = 0;
while(true)
{
mLog.debug("Playback started [" + path.toString() + "]");
toAlias.setName("Playback #" + playCount++);
try (AudioPacketMonoWaveReader reader = new AudioPacketMonoWaveReader(path, true))
{
reader.setMetadata(metadata);
reader.setListener(audioBroadcaster);
reader.read();
audioBroadcaster.receive(new AudioPacket(AudioPacket.Type.END, metadata));
}
catch (IOException e)
{
mLog.error("Error", e);
}
mLog.debug("Playback ended [" + path.toString() + "]");
}
}
}
}

View File

@@ -108,8 +108,6 @@ public class IcecastTCPConfiguration extends BroadcastConfiguration
sb.append(getPassword());
}
mLog.debug("Connection String: " + sb.toString());
String base64 = Base64.getEncoder().encodeToString(sb.toString().getBytes());
return "Basic " + base64;

View File

@@ -0,0 +1,269 @@
/*******************************************************************************
* 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.icecast;
import alias.AliasModel;
import audio.broadcast.BroadcastConfiguration;
import audio.broadcast.BroadcastConfigurationEditor;
import audio.broadcast.BroadcastEvent;
import audio.broadcast.BroadcastModel;
import audio.broadcast.BroadcastServerType;
import audio.broadcast.broadcastify.BroadcastifyConfiguration;
import gui.editor.DocumentListenerEditor;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import settings.SettingsManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IcecastTCPConfigurationEditor extends BroadcastConfigurationEditor
{
private final static Logger mLog = LoggerFactory.getLogger( IcecastTCPConfigurationEditor.class );
private JTextField mName;
private JTextField mServer;
private JTextField mPort;
private JTextField mMountPoint;
private JTextField mPassword;
private JButton mSaveButton;
private JButton mResetButton;
private JCheckBox mEnabled;
public IcecastTCPConfigurationEditor(BroadcastModel broadcastModel, AliasModel aliasModel,
SettingsManager settingsManager)
{
super(broadcastModel, aliasModel, settingsManager);
init();
}
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[align right][grow,fill]", "[][][][][][][][][][grow,fill]" ) );
setPreferredSize(new Dimension(150,400));
JLabel channelLabel = new JLabel("Icecast 2.3 Stream");
ImageIcon icon = mSettingsManager.getImageIcon(BroadcastServerType.ICECAST_TCP.getIconName(), 25);
channelLabel.setIcon(icon);
add(channelLabel, "span, align center");
add(new JLabel("Name:"));
mName = new JTextField();
mName.getDocument().addDocumentListener(this);
mName.setToolTipText("Unique name for this stream");
add(mName);
add(new JLabel("Server:"));
mServer = new JTextField();
mServer.getDocument().addDocumentListener(this);
mServer.setToolTipText("Server address (e.g. audio1.icecast.com or localhost)");
add(mServer);
add(new JLabel("Port:"));
mPort = new JTextField();
mPort.getDocument().addDocumentListener(this);
mPort.setToolTipText("Server port number (e.g. 80)");
add(mPort);
add(new JLabel("Mount:"));
mMountPoint = new JTextField();
mMountPoint.getDocument().addDocumentListener(this);
mMountPoint.setToolTipText("Mount point (e.g. \\12345)");
add(mMountPoint);
add(new JLabel("Password:"));
mPassword = new JTextField();
mPassword.getDocument().addDocumentListener(this);
mPassword.setToolTipText("Password for the stream");
add(mPassword);
mEnabled = new JCheckBox("Enabled");
mEnabled.setToolTipText("Enable (checked) or disable this stream");
mEnabled.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
setModified(true);
}
});
add(mEnabled, "span");
mSaveButton = new JButton("Save");
mSaveButton.setEnabled(false);
mSaveButton.setToolTipText("Click to save configuration information");
mSaveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
save();
}
});
add(mSaveButton);
mResetButton = new JButton("Reset");
mResetButton.setEnabled(false);
mResetButton.setToolTipText("Click to reset any changes you've made since the last save");
mResetButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
setModified(false);
setItem(getItem());
}
});
add(mResetButton);
}
@Override
public void setModified(boolean modified)
{
super.setModified(modified);
mSaveButton.setEnabled(modified);
mResetButton.setEnabled(modified);
}
@Override
public void setItem(BroadcastConfiguration item)
{
super.setItem(item);
if(hasItem())
{
IcecastTCPConfiguration config = (IcecastTCPConfiguration)getItem();
mName.setText(config.getName());
mServer.setText(config.getHost());
mPort.setText(config.getPort() != 0 ? String.valueOf(config.getPort()) : null);
mMountPoint.setText(config.getMountPoint());
mPassword.setText(config.getPassword());
mEnabled.setSelected(config.isEnabled());
}
else
{
mName.setText(null);
mServer.setText(null);
mPort.setText(null);
mMountPoint.setText(null);
mPassword.setText(null);
mEnabled.setSelected(false);
}
setModified(false);
}
@Override
public void save()
{
IcecastTCPConfiguration config = (IcecastTCPConfiguration)getItem();
if(validateConfiguration())
{
updateConfigurationName(config, mName.getText());
config.setHost(mServer.getText());
config.setPort(getPort());
config.setMountPoint(mMountPoint.getText());
config.setPassword(mPassword.getText());
config.setEnabled(mEnabled.isSelected());
setModified(false);
mBroadcastModel.process(new BroadcastEvent(getItem(), BroadcastEvent.Event.CONFIGURATION_CHANGE));
}
}
/**
* Validates the user specified values in the controls prior to saving them to the configuration
*/
private boolean validateConfiguration()
{
String name = mName.getText();
//A unique stream name is required
if(!mBroadcastModel.isUniqueName(name, getItem()))
{
String message = (name == null || name.isEmpty()) ?
"Please specify a stream name." : "Stream name " + name +
"is already in use.\nPlease choose another name.";
JOptionPane.showMessageDialog(IcecastTCPConfigurationEditor.this,
message, "Invalid Stream Name", JOptionPane.ERROR_MESSAGE);
mName.requestFocus();
return false;
}
//Server address is optional, but required
if(!validateTextField(mServer, "Invalid Server Address", "Please specify a server address."))
{
return true;
}
//Port is optional, but required
if(!validateIntegerTextField(mPort, "Invalid Port Number", "Please specify a port number (1 <> 65535)", 1, 65535))
{
return true;
}
//Mount Point is optional, but required
if(!validateTextField(mMountPoint, "Invalid Mount Point", "Please specify a mount point."))
{
return true;
}
//Password is optional, but required
if(!validateTextField(mPassword, "Invalid Password", "Please specify a password."))
{
return true;
}
return true;
}
/**
* Parses an Integer from the port text control or returns 0 if the control doesn't contain an integer value.
*/
private int getPort()
{
String port = mPort.getText();
if(port != null && !port.isEmpty())
{
try
{
return Integer.parseInt(port);
}
catch(Exception e)
{
//Do nothing, we couldn't parse the number value
}
}
return 0;
}
}