mirror of
https://github.com/DSheirer/sdrtrunk.git
synced 2026-11-17 11:07:35 -05:00
#30 - WIP - adds Icecast TCP(v2.3) and HTTP(v2.4) server support. Adds streaming tab and ability to add/delete/change streaming configurations. Adds streaming channel alias id so that aliases can be tagged to stream to one or more stream channels. Adds initial support for broadcastify streaming.
This commit is contained in:
447
src/audio/broadcast/icecast/IcecastHTTPBroadcaster.java
Normal file
447
src/audio/broadcast/icecast/IcecastHTTPBroadcaster.java
Normal file
@@ -0,0 +1,447 @@
|
||||
/*******************************************************************************
|
||||
* 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 audio.AudioPacket;
|
||||
import audio.broadcast.BroadcastFormat;
|
||||
import audio.broadcast.BroadcastState;
|
||||
import audio.broadcast.Broadcaster;
|
||||
import audio.broadcast.BroadcastFactory;
|
||||
import audio.convert.IAudioConverter;
|
||||
import controller.ThreadPoolManager;
|
||||
import org.asynchttpclient.AsyncHandler;
|
||||
import org.asynchttpclient.BoundRequestBuilder;
|
||||
import org.asynchttpclient.DefaultAsyncHttpClient;
|
||||
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
|
||||
import org.asynchttpclient.HttpResponseBodyPart;
|
||||
import org.asynchttpclient.HttpResponseHeaders;
|
||||
import org.asynchttpclient.HttpResponseStatus;
|
||||
import org.asynchttpclient.ListenableFuture;
|
||||
import org.asynchttpclient.Realm;
|
||||
import org.asynchttpclient.Response;
|
||||
import org.asynchttpclient.uri.Uri;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscriber;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import properties.SystemProperties;
|
||||
import record.wave.AudioPacketMonoWaveReader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class IcecastHTTPBroadcaster extends Broadcaster implements Publisher<ByteBuffer>
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger( IcecastHTTPBroadcaster.class );
|
||||
|
||||
private static final String HTTP_100_CONTINUE = "100-continue";
|
||||
private static final long RECONNECT_INTERVAL_MILLISECONDS = 15000; //15 seconds
|
||||
private long mLastConnectionAttempt = 0;
|
||||
private DefaultAsyncHttpClient mAsyncHttpClient;
|
||||
private Subscriber<? super ByteBuffer> mSubscriber;
|
||||
private List<AudioPacket> mPacketsToBroadcast = new ArrayList<>();
|
||||
private ConvertedAudioStreamSubscription mSubscription;
|
||||
private AtomicBoolean mConnecting = new AtomicBoolean();
|
||||
|
||||
/**
|
||||
* Creates an Icecast 2.4.x (or newer) compatible broadcaster using HTTP 1.1 protocol
|
||||
*
|
||||
* Note: use @see IcecastTCPBroadcaster for Icecast version 2.3.x and older.
|
||||
* @param configuration
|
||||
* @param audioConverter
|
||||
*/
|
||||
public IcecastHTTPBroadcaster(ThreadPoolManager threadPoolManager,
|
||||
IcecastHTTPConfiguration configuration,
|
||||
IAudioConverter audioConverter)
|
||||
{
|
||||
super(threadPoolManager, configuration, audioConverter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration information
|
||||
*/
|
||||
private IcecastHTTPConfiguration getConfiguration()
|
||||
{
|
||||
return (IcecastHTTPConfiguration)getBroadcastConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast any queued audio packets using Icecast V2 Protocol
|
||||
*/
|
||||
@Override
|
||||
public void broadcast()
|
||||
{
|
||||
if(connect())
|
||||
{
|
||||
if (mSubscription != null && mSubscription.hasDemand())
|
||||
{
|
||||
mAudioQueue.drainTo(mPacketsToBroadcast, 5);
|
||||
|
||||
if (!mPacketsToBroadcast.isEmpty())
|
||||
{
|
||||
byte[] convertedAudio = getAudioConverter().convert(mPacketsToBroadcast);
|
||||
|
||||
mLog.debug("We have [" + mPacketsToBroadcast.size() +
|
||||
"] packets - sending:" + convertedAudio.length + " bytes");
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.wrap(convertedAudio);
|
||||
|
||||
mSubscription.broadcast(buffer);
|
||||
|
||||
mPacketsToBroadcast.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<? super ByteBuffer> subscriber)
|
||||
{
|
||||
//Remove existing subscription, if there is one
|
||||
if (mSubscription != null)
|
||||
{
|
||||
mSubscription.cancel();
|
||||
}
|
||||
|
||||
//Create the subscription
|
||||
mSubscription = new ConvertedAudioStreamSubscription(subscriber);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(canConnect())
|
||||
{
|
||||
createConnection();
|
||||
}
|
||||
|
||||
return connected();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Disconnect from the remote server
|
||||
*/
|
||||
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(mConnecting.compareAndSet(false, true))
|
||||
{
|
||||
if(canConnect() && System.currentTimeMillis() - mLastConnectionAttempt >= RECONNECT_INTERVAL_MILLISECONDS)
|
||||
{
|
||||
mLog.debug("Creating a connection to icecast server");
|
||||
mLastConnectionAttempt = System.currentTimeMillis();
|
||||
|
||||
DefaultAsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
|
||||
.setReadTimeout(-1)
|
||||
.setRequestTimeout(-1)
|
||||
.build();
|
||||
|
||||
mAsyncHttpClient = new DefaultAsyncHttpClient(config);
|
||||
|
||||
Uri uri = new Uri(Uri.HTTP, null, getConfiguration().getHost(), getConfiguration().getPort(),
|
||||
getConfiguration().getMountPoint(), null);
|
||||
|
||||
mLog.debug("URL:" + uri.toUrl());
|
||||
|
||||
BoundRequestBuilder builder = mAsyncHttpClient.preparePut(uri.toUrl());
|
||||
|
||||
//Use Basic (base64) authentication
|
||||
Realm realm = new Realm.Builder(getConfiguration().getUserName(), getConfiguration().getPassword())
|
||||
.setScheme(Realm.AuthScheme.BASIC).setUsePreemptiveAuth(true).build();
|
||||
builder.setRealm(realm);
|
||||
builder.setBody(this);
|
||||
|
||||
builder.addHeader(IcecastHeader.ACCEPT.getValue(), "*/*");
|
||||
builder.addHeader(IcecastHeader.CONTENT_TYPE.getValue(), getConfiguration().getBroadcastFormat().getValue());
|
||||
builder.addHeader(IcecastHeader.PUBLIC.getValue(), getConfiguration().isPublic() ? "1" : "0");
|
||||
|
||||
if(getConfiguration().hasName())
|
||||
{
|
||||
builder.addHeader(IcecastHeader.NAME.getValue(), getConfiguration().getName());
|
||||
}
|
||||
|
||||
if(getConfiguration().hasDescription())
|
||||
{
|
||||
builder.addHeader(IcecastHeader.DESCRIPTION.getValue(), getConfiguration().getDescription());
|
||||
}
|
||||
|
||||
if(getConfiguration().hasURL())
|
||||
{
|
||||
builder.addHeader(IcecastHeader.URL.getValue(), getConfiguration().getURL());
|
||||
}
|
||||
|
||||
if(getConfiguration().hasGenre())
|
||||
{
|
||||
builder.addHeader(IcecastHeader.GENRE.getValue(), getConfiguration().getGenre());
|
||||
}
|
||||
|
||||
|
||||
if(getConfiguration().hasBitRate())
|
||||
{
|
||||
builder.addHeader(IcecastHeader.BITRATE.getValue(), String.valueOf(getConfiguration().getBitRate()));
|
||||
}
|
||||
|
||||
builder.addHeader(IcecastHeader.USER_AGENT.getValue(),
|
||||
SystemProperties.getInstance().getApplicationName());
|
||||
|
||||
builder.addHeader(IcecastHeader.EXPECT.getValue(), HTTP_100_CONTINUE);
|
||||
|
||||
ListenableFuture<Response> future = builder.execute(new AsyncHttpConnectionResponseHandler());
|
||||
|
||||
mLog.debug("Create connection was submitted asynchronously");
|
||||
}
|
||||
else
|
||||
{
|
||||
mConnecting.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class AsyncHttpConnectionResponseHandler implements AsyncHandler<Response>
|
||||
{
|
||||
@Override
|
||||
public void onThrowable(Throwable throwable)
|
||||
{
|
||||
mLog.error("BROADCAST error", throwable);
|
||||
setBroadcastState(BroadcastState.BROADCAST_ERROR);
|
||||
mConnecting.compareAndSet(true, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onBodyPartReceived(HttpResponseBodyPart httpResponseBodyPart) throws Exception
|
||||
{
|
||||
mLog.debug("Got response body part");
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onStatusReceived(HttpResponseStatus httpResponseStatus) throws Exception
|
||||
{
|
||||
mLog.debug("Got response status: " + httpResponseStatus.toString());
|
||||
State returnState = State.ABORT;
|
||||
|
||||
switch(httpResponseStatus.getStatusCode())
|
||||
{
|
||||
case 200: //200-OK
|
||||
setBroadcastState(BroadcastState.CONNECTED);
|
||||
returnState = State.CONTINUE;
|
||||
break;
|
||||
case 100: //100-Continue
|
||||
setBroadcastState(BroadcastState.CONNECTING);
|
||||
returnState = State.CONTINUE;
|
||||
break;
|
||||
case 401:
|
||||
setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
break;
|
||||
case 403:
|
||||
String text = httpResponseStatus.getStatusText();
|
||||
|
||||
mLog.error("Error while connecting to Icecast server: " + httpResponseStatus.getStatusCode() +
|
||||
" " + text);
|
||||
|
||||
if(text != null)
|
||||
{
|
||||
if(text.contains("Content-type not supported"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.UNSUPPORTED_AUDIO_FORMAT);
|
||||
}
|
||||
else if(text.contains("too many sources"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.MAX_SOURCES_EXCEEDED);
|
||||
}
|
||||
else if(text.contains("Mountpoint in use"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.MOUNT_POINT_IN_USE);
|
||||
}
|
||||
else
|
||||
{
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
break;
|
||||
case 500:
|
||||
mLog.error("Error while connecting to Icecast server: " + httpResponseStatus.getStatusCode() +
|
||||
" " + httpResponseStatus.getStatusText());
|
||||
setBroadcastState(BroadcastState.REMOTE_SERVER_ERROR);
|
||||
break;
|
||||
default:
|
||||
mLog.error("Error while connecting to Icecast server - unrecognized status code: " +
|
||||
httpResponseStatus.getStatusCode() + " " + httpResponseStatus.getStatusText());
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
|
||||
mConnecting.compareAndSet(true, false);
|
||||
|
||||
return returnState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onHeadersReceived(HttpResponseHeaders httpResponseHeaders) throws Exception
|
||||
{
|
||||
mLog.debug("Got response headers!");
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response onCompleted() throws Exception
|
||||
{
|
||||
mLog.debug("We're completed");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscription to monitor a converted audio stream subscriber and the subscriber's expressed demand for converted
|
||||
* audio byte buffers
|
||||
*/
|
||||
public class ConvertedAudioStreamSubscription implements Subscription
|
||||
{
|
||||
private Subscriber<? super ByteBuffer> mSubscriber;
|
||||
private AtomicLong mDemand = new AtomicLong();
|
||||
|
||||
/**
|
||||
* Constructs a subscription
|
||||
* @param subscriber to receive converted audio byte buffers
|
||||
*/
|
||||
public ConvertedAudioStreamSubscription(Subscriber<? super ByteBuffer> subscriber)
|
||||
{
|
||||
mSubscriber = subscriber;
|
||||
mSubscriber.onSubscribe(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request method for the subscriber to register demand for audio byte buffers
|
||||
* @param requestedBufferCount to stream to the subscriber
|
||||
*/
|
||||
@Override
|
||||
public void request(long requestedBufferCount)
|
||||
{
|
||||
mDemand.getAndAdd(requestedBufferCount);
|
||||
|
||||
mLog.debug("Subscriber request:" + requestedBufferCount + " outstanding demand: " + mDemand.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this subscription currently has registered demand from the subscriber
|
||||
*/
|
||||
public boolean hasDemand()
|
||||
{
|
||||
return mDemand.get() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts the buffer to the subscriber and decrements the internal buffer demand counter
|
||||
*/
|
||||
public void broadcast(ByteBuffer buffer)
|
||||
{
|
||||
if(mSubscriber != null)
|
||||
{
|
||||
mSubscriber.onNext(buffer);
|
||||
mDemand.decrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked by the subscriber to cancel the stream
|
||||
*/
|
||||
@Override
|
||||
public void cancel()
|
||||
{
|
||||
mLog.debug("Subscriber has requested a cancel");
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
boolean test = false;
|
||||
|
||||
IcecastHTTPConfiguration config = new IcecastHTTPConfiguration(BroadcastFormat.MP3);
|
||||
|
||||
config.setName("Broadcastify SDRTrunk Test #2");
|
||||
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(true);
|
||||
config.setURL("http://www.radioreference.com");
|
||||
config.setBitRate(16);
|
||||
|
||||
if(test)
|
||||
{
|
||||
mLog.debug("Auth:" + config.getEncodedCredentials());
|
||||
}
|
||||
else
|
||||
{
|
||||
ThreadPoolManager threadPoolManager = new ThreadPoolManager();
|
||||
|
||||
final Broadcaster broadcaster = BroadcastFactory.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() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,19 +24,23 @@ import audio.broadcast.BroadcastServerType;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
public class IcecastConfiguration extends BroadcastConfiguration
|
||||
public class IcecastHTTPConfiguration extends BroadcastConfiguration
|
||||
{
|
||||
private String mUserName;
|
||||
private String mMountPoint;
|
||||
private String mStreamName;
|
||||
private String mDescription;
|
||||
private String mGenre;
|
||||
private boolean mPublic;
|
||||
private int mChannels;
|
||||
private int mBitRate;
|
||||
private int mChannels = 1;
|
||||
private int mSampleRate = 8000;
|
||||
private String mURL;
|
||||
|
||||
public IcecastConfiguration(BroadcastFormat format)
|
||||
/**
|
||||
* Icecast 2.3.x and 2.4.x compatible configuration
|
||||
* @param format
|
||||
*/
|
||||
public IcecastHTTPConfiguration(BroadcastFormat format)
|
||||
{
|
||||
super(format);
|
||||
}
|
||||
@@ -44,16 +48,24 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
@Override
|
||||
public BroadcastServerType getBroadcastServerType()
|
||||
{
|
||||
return BroadcastServerType.ICECAST;
|
||||
return BroadcastServerType.ICECAST_HTTP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64 encoded version of the username and password with prepended 'Basic ' tag.
|
||||
*/
|
||||
public String getAuthorization()
|
||||
public String getEncodedCredentials()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(getUserName()).append(":").append(getPassword());
|
||||
|
||||
if(hasUserName())
|
||||
{
|
||||
sb.append(getUserName()).append(":").append(getPassword());
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.append(getPassword());
|
||||
}
|
||||
|
||||
String base64 = Base64.getEncoder().encodeToString(sb.toString().getBytes());
|
||||
|
||||
@@ -70,6 +82,11 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mUserName = userName;
|
||||
}
|
||||
|
||||
public boolean hasUserName()
|
||||
{
|
||||
return mUserName != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount point or path to the stream
|
||||
* @return mount point
|
||||
@@ -88,21 +105,9 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mMountPoint = mountPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream name
|
||||
*/
|
||||
public String getStreamName()
|
||||
public boolean hasMountPoint()
|
||||
{
|
||||
return mStreamName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the stream name
|
||||
* @param name
|
||||
*/
|
||||
public void setStreamName(String name)
|
||||
{
|
||||
mStreamName = name;
|
||||
return mMountPoint != null;
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +121,11 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mDescription = description;
|
||||
}
|
||||
|
||||
public boolean hasDescription()
|
||||
{
|
||||
return mDescription != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream genre
|
||||
*/
|
||||
@@ -133,6 +143,11 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mGenre = genre;
|
||||
}
|
||||
|
||||
public boolean hasGenre()
|
||||
{
|
||||
return mGenre != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public visibility of the broadcast
|
||||
*/
|
||||
@@ -166,6 +181,11 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mChannels = channels;
|
||||
}
|
||||
|
||||
public boolean hasChannels()
|
||||
{
|
||||
return mChannels > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bit rate in bits per second
|
||||
*/
|
||||
@@ -183,6 +203,26 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
mBitRate = bitRate;
|
||||
}
|
||||
|
||||
public boolean hasBitRate()
|
||||
{
|
||||
return mBitRate > 0;
|
||||
}
|
||||
|
||||
public int getSampleRate()
|
||||
{
|
||||
return mSampleRate;
|
||||
}
|
||||
|
||||
public void setSampleRate(int sampleRate)
|
||||
{
|
||||
mSampleRate = sampleRate;
|
||||
}
|
||||
|
||||
public boolean hasSampleRate()
|
||||
{
|
||||
return mSampleRate > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL associated with the broadcast where users can find additional details.
|
||||
*/
|
||||
@@ -199,4 +239,9 @@ public class IcecastConfiguration extends BroadcastConfiguration
|
||||
{
|
||||
mURL = url;
|
||||
}
|
||||
|
||||
public boolean hasURL()
|
||||
{
|
||||
return mURL != null;
|
||||
}
|
||||
}
|
||||
@@ -1,574 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* 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 audio.AudioPacket;
|
||||
import audio.broadcast.BroadcastFormat;
|
||||
import audio.broadcast.BroadcastHandler;
|
||||
import audio.broadcast.BroadcastState;
|
||||
import audio.broadcast.Broadcaster;
|
||||
import audio.broadcast.BroadcasterFactory;
|
||||
import audio.broadcast.HttpAsyncAudioStreamer2;
|
||||
import audio.convert.IAudioConverter;
|
||||
import controller.ThreadPoolManager;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.HttpVersion;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.concurrent.FutureCallback;
|
||||
import org.apache.http.entity.AbstractHttpEntity;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
|
||||
import org.apache.http.impl.nio.client.HttpAsyncClients;
|
||||
import org.apache.http.nio.ContentDecoder;
|
||||
import org.apache.http.nio.IOControl;
|
||||
import org.apache.http.nio.protocol.BasicAsyncResponseConsumer;
|
||||
import org.apache.http.protocol.HTTP;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import properties.SystemProperties;
|
||||
import record.wave.AudioPacketMonoWaveReader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class IcecastHandler extends BroadcastHandler
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger( IcecastHandler.class );
|
||||
|
||||
private static final String HTTP_100_CONTINUE = "100-continue";
|
||||
private static final long RECONNECT_INTERVAL_MILLISECONDS = 15000; //15 seconds
|
||||
private long mLastConnectionAttempt = 0;
|
||||
private CloseableHttpAsyncClient mHttpClient;
|
||||
private HttpAsyncAudioStreamer2 mAudioStreamer;
|
||||
private HttpHost mHttpHost;
|
||||
private HttpRequest mHttpRequest;
|
||||
private int mCounter = 0;
|
||||
|
||||
/**
|
||||
* Creates an Icecast broadcast handler.
|
||||
* @param configuration
|
||||
* @param audioConverter
|
||||
*/
|
||||
public IcecastHandler(IcecastConfiguration configuration, IAudioConverter audioConverter)
|
||||
{
|
||||
super(configuration, audioConverter);
|
||||
|
||||
try
|
||||
{
|
||||
HttpRequest httpRequest = getHttpRequest();
|
||||
mAudioStreamer = new HttpAsyncAudioStreamer2(getHttpHost(), httpRequest,
|
||||
getAudioConverter(), 20);
|
||||
}
|
||||
catch(URISyntaxException use)
|
||||
{
|
||||
mLog.error("Error creating URI from configuration", use);
|
||||
setBroadcastState(BroadcastState.UNKNOWN_HOST);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration information
|
||||
*/
|
||||
private IcecastConfiguration getConfiguration()
|
||||
{
|
||||
return (IcecastConfiguration)getBroadcastConfiguration();
|
||||
}
|
||||
|
||||
private HttpHost getHttpHost()
|
||||
{
|
||||
if(mHttpHost == null)
|
||||
{
|
||||
mHttpHost = new HttpHost(getConfiguration().getHost(), getConfiguration().getPort());
|
||||
}
|
||||
|
||||
return mHttpHost;
|
||||
}
|
||||
|
||||
private URI getURI() throws URISyntaxException
|
||||
{
|
||||
return new URIBuilder()
|
||||
.setScheme("http")
|
||||
.setHost(getConfiguration().getHost())
|
||||
.setPort(getConfiguration().getPort())
|
||||
.setPath(getConfiguration().getMountPoint())
|
||||
.build();
|
||||
}
|
||||
|
||||
private HttpRequest getHttpRequest() throws URISyntaxException
|
||||
{
|
||||
if(mHttpRequest == null)
|
||||
{
|
||||
HttpPut httpPut = new HttpPut(getURI());
|
||||
httpPut.setProtocolVersion(HttpVersion.HTTP_1_1);
|
||||
|
||||
httpPut.setEntity(new MyHttpEntity(getConfiguration().getBroadcastFormat()));
|
||||
|
||||
mHttpRequest = httpPut;
|
||||
mHttpRequest.addHeader(IcecastHeader.AUTHORIZATION.getValue(), getConfiguration().getAuthorization());
|
||||
mHttpRequest.addHeader(IcecastHeader.ACCEPT.getValue(), "*/*");
|
||||
mHttpRequest.addHeader(IcecastHeader.CONTENT_TYPE.getValue(), getConfiguration().getBroadcastFormat().getValue());
|
||||
mHttpRequest.addHeader(IcecastHeader.PUBLIC.getValue(), getConfiguration().isPublic() ? "1" : "0");
|
||||
mHttpRequest.addHeader(IcecastHeader.NAME.getValue(), getConfiguration().getStreamName());
|
||||
mHttpRequest.addHeader(IcecastHeader.DESCRIPTION.getValue(), getConfiguration().getHost());
|
||||
mHttpRequest.addHeader(IcecastHeader.URL.getValue(), getConfiguration().getURL());
|
||||
mHttpRequest.addHeader(IcecastHeader.GENRE.getValue(), getConfiguration().getGenre());
|
||||
mHttpRequest.addHeader(IcecastHeader.USER_AGENT.getValue(), SystemProperties.getInstance().getApplicationName());
|
||||
mHttpRequest.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
|
||||
}
|
||||
|
||||
return mHttpRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process audio packets using Shoutcast V1 Protocol
|
||||
* @param audioPackets
|
||||
*/
|
||||
@Override
|
||||
public void broadcast(List<AudioPacket> audioPackets)
|
||||
{
|
||||
if(mCounter > 1)
|
||||
{
|
||||
mLog.debug("Connecting ...");
|
||||
connect();
|
||||
}
|
||||
|
||||
for(AudioPacket audioPacket: audioPackets)
|
||||
{
|
||||
mAudioStreamer.receive(audioPacket);
|
||||
|
||||
mCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
mLog.debug("Creating a connection to icecast server");
|
||||
mLastConnectionAttempt = System.currentTimeMillis();
|
||||
|
||||
if(mHttpClient == null)
|
||||
{
|
||||
mHttpClient = HttpAsyncClients.createDefault();
|
||||
mHttpClient.start();
|
||||
}
|
||||
|
||||
// try
|
||||
// {
|
||||
// mAudioStreamer.addHeader(IcecastHeader.EXPECT.getValue(), HTTP_100_CONTINUE);
|
||||
|
||||
|
||||
// BasicAsyncRequestProducer producer = new BasicAsyncRequestProducer(httpHost, mAudioStreamer);
|
||||
// BasicAsyncRequestProducer producer = new MyProducer(httpHost, mAudioStreamer, mAudioStreamer);
|
||||
// HttpAsyncRequestProducer producer = new HttpAsyncAudioStreamer2(httpHost, getConfiguration().getBroadcastFormat(),
|
||||
// getAudioConverter(), 2000);
|
||||
|
||||
|
||||
// AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>()
|
||||
// {
|
||||
// @Override
|
||||
// protected void onCharReceived(CharBuffer charBuffer, IOControl ioControl) throws IOException
|
||||
// {
|
||||
// mLog.debug("Received consumer characters!");
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// protected void onResponseReceived(HttpResponse response) throws HttpException, IOException
|
||||
// {
|
||||
// mLog.debug("Received consumer response:\n" + response.toString());
|
||||
//
|
||||
// switch(response.getStatusLine().getStatusCode())
|
||||
// {
|
||||
// case HttpStatus.SC_OK: //200
|
||||
// case HttpStatus.SC_CONTINUE: //100
|
||||
// mLog.debug("Connected to icecast server");
|
||||
// setBroadcastState(BroadcastState.CONNECTED);
|
||||
// break;
|
||||
// case HttpStatus.SC_UNAUTHORIZED: //401
|
||||
// setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
// mLog.error("Couldn't connect to Icecast2 server using login credentials");
|
||||
// break;
|
||||
// case HttpStatus.SC_FORBIDDEN: //403
|
||||
// String reason = response.getStatusLine().getReasonPhrase();
|
||||
//
|
||||
// if(reason.contains("Content-Type"))
|
||||
// {
|
||||
// setBroadcastState(BroadcastState.UNSUPPORTED_AUDIO_FORMAT);
|
||||
// mLog.error("Icecast2 server does not support audio format");
|
||||
// }
|
||||
// else if(reason.startsWith("internal format"))
|
||||
// {
|
||||
// setBroadcastState(BroadcastState.REMOTE_SERVER_ERROR);
|
||||
// mLog.error("Icecast2 server has an error");
|
||||
// }
|
||||
// else if(reason.startsWith("too many sources"))
|
||||
// {
|
||||
// setBroadcastState(BroadcastState.MAX_SOURCES_EXCEEDED);
|
||||
// mLog.error("Icecast2 server maximum number of sources exceeded");
|
||||
// }
|
||||
// else if(reason.startsWith("Mountpoint"))
|
||||
// {
|
||||
// setBroadcastState(BroadcastState.MOUNT_POINT_IN_USE);
|
||||
// mLog.error("Icecast2 server mount point is already in use");
|
||||
// }
|
||||
// case HttpStatus.SC_INTERNAL_SERVER_ERROR: //500
|
||||
// setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
// mLog.error("Couldn't connect to Icecast2 server using login credentials");
|
||||
// break;
|
||||
// default:
|
||||
// setBroadcastState(BroadcastState.ERROR);
|
||||
// mLog.error("Error connecting to remote server. HTTP Status Code:" +
|
||||
// response.getStatusLine().getStatusCode() + " Reason:" +
|
||||
// response.getStatusLine().getReasonPhrase());
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// protected HttpResponse buildResult(HttpContext httpContext) throws Exception
|
||||
// {
|
||||
// mLog.debug("Received consumer request for response!!!!!!");
|
||||
// return null;
|
||||
// }
|
||||
// };
|
||||
|
||||
MyConsumer consumer = new MyConsumer();
|
||||
|
||||
mLog.debug("Sending connection request");
|
||||
Future<HttpResponse> response = mHttpClient.execute(mAudioStreamer, consumer, new FutureCallback<HttpResponse>()
|
||||
{
|
||||
@Override
|
||||
public void completed(HttpResponse httpResponse)
|
||||
{
|
||||
mLog.debug("Received final response:\n" + httpResponse.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Exception e)
|
||||
{
|
||||
mLog.debug("Received final response error", e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelled()
|
||||
{
|
||||
mLog.debug("Received final response - cancelled");
|
||||
}
|
||||
});
|
||||
|
||||
mLog.debug("Create connection finished ... processing");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
boolean test = false;
|
||||
|
||||
IcecastConfiguration config = new IcecastConfiguration(BroadcastFormat.MP3);
|
||||
config.setAlias("Test Configuration");
|
||||
config.setHost("localhost");
|
||||
config.setPort(8000);
|
||||
config.setMountPoint("/dennyTestStream");
|
||||
config.setUserName("source");
|
||||
config.setPassword("denny");
|
||||
config.setStreamName("Denny's Audio Broadcast Test");
|
||||
config.setDescription("Description");
|
||||
config.setGenre("Scanner Audio");
|
||||
config.setPublic(true);
|
||||
config.setURL("http://localhost:8000");
|
||||
config.setBitRate(16);
|
||||
|
||||
if(test)
|
||||
{
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
|
||||
URI uri;
|
||||
|
||||
try
|
||||
{
|
||||
uri = new URIBuilder()
|
||||
.setScheme("http")
|
||||
.setHost(config.getHost())
|
||||
.setPort(config.getPort())
|
||||
.setPath(config.getMountPoint())
|
||||
.build();
|
||||
|
||||
HttpPut httpPut = new HttpPut(uri);
|
||||
httpPut.setProtocolVersion(HttpVersion.HTTP_1_1);
|
||||
|
||||
httpPut.addHeader(IcecastHeader.AUTHORIZATION.getValue(), config.getAuthorization());
|
||||
httpPut.addHeader(IcecastHeader.HOST.getValue(), config.getHost());
|
||||
httpPut.addHeader(IcecastHeader.ACCEPT.getValue(), "*/*");
|
||||
httpPut.addHeader(IcecastHeader.CONTENT_TYPE.getValue(), config.getBroadcastFormat().getValue());
|
||||
httpPut.addHeader(IcecastHeader.PUBLIC.getValue(), config.isPublic() ? "1" : "0");
|
||||
httpPut.addHeader(IcecastHeader.NAME.getValue(), config.getStreamName());
|
||||
httpPut.addHeader(IcecastHeader.DESCRIPTION.getValue(), config.getHost());
|
||||
httpPut.addHeader(IcecastHeader.URL.getValue(), config.getURL());
|
||||
httpPut.addHeader(IcecastHeader.GENRE.getValue(), config.getGenre());
|
||||
httpPut.addHeader(IcecastHeader.USER_AGENT.getValue(), SystemProperties.getInstance().getApplicationName());
|
||||
httpPut.addHeader(IcecastHeader.EXPECT.getValue(), HTTP_100_CONTINUE);
|
||||
|
||||
CloseableHttpResponse response = client.execute(httpPut);
|
||||
|
||||
mLog.debug("Response:" + response.toString());
|
||||
|
||||
}
|
||||
catch(URISyntaxException e)
|
||||
{
|
||||
mLog.error("URI syntax exception", e);
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.error("IO Exception", ioe);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
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() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MyHttpEntity extends AbstractHttpEntity
|
||||
{
|
||||
public MyHttpEntity(BroadcastFormat broadcastFormat)
|
||||
{
|
||||
super.setContentType(broadcastFormat.getValue());
|
||||
super.setChunked(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRepeatable()
|
||||
{
|
||||
mLog.debug("MyEntity - isRepeatable() invoked");
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getContentLength()
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getContent() throws IOException, UnsupportedOperationException
|
||||
{
|
||||
mLog.debug("MyEntity - getContent() invoked");
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(OutputStream outputStream) throws IOException
|
||||
{
|
||||
mLog.debug("MyEntity - writeTo() invoked");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStreaming()
|
||||
{
|
||||
mLog.debug("MyEntity - isStreaming() invoked");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public class MyConsumer extends BasicAsyncResponseConsumer
|
||||
{
|
||||
public MyConsumer()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResponseReceived(HttpResponse response) throws IOException
|
||||
{
|
||||
mLog.debug("MyConsumer onResponseReceived() " + response.toString());
|
||||
|
||||
super.onResponseReceived(response);
|
||||
|
||||
switch(response.getStatusLine().getStatusCode())
|
||||
{
|
||||
case HttpStatus.SC_OK: //200
|
||||
case HttpStatus.SC_CONTINUE: //100
|
||||
mLog.debug("Connected to icecast server");
|
||||
setBroadcastState(BroadcastState.CONNECTED);
|
||||
break;
|
||||
case HttpStatus.SC_UNAUTHORIZED: //401
|
||||
setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
mLog.error("Couldn't connect to Icecast2 server using login credentials");
|
||||
break;
|
||||
case HttpStatus.SC_FORBIDDEN: //403
|
||||
String reason = response.getStatusLine().getReasonPhrase();
|
||||
|
||||
if(reason.contains("Content-Type"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.UNSUPPORTED_AUDIO_FORMAT);
|
||||
mLog.error("Icecast2 server does not support audio format");
|
||||
}
|
||||
else if(reason.startsWith("internal format"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.REMOTE_SERVER_ERROR);
|
||||
mLog.error("Icecast2 server has an error");
|
||||
}
|
||||
else if(reason.startsWith("too many sources"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.MAX_SOURCES_EXCEEDED);
|
||||
mLog.error("Icecast2 server maximum number of sources exceeded");
|
||||
}
|
||||
else if(reason.startsWith("Mountpoint"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.MOUNT_POINT_IN_USE);
|
||||
mLog.error("Icecast2 server mount point is already in use");
|
||||
}
|
||||
case HttpStatus.SC_INTERNAL_SERVER_ERROR: //500
|
||||
setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
mLog.error("Couldn't connect to Icecast2 server using login credentials");
|
||||
break;
|
||||
default:
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
mLog.error("Error connecting to remote server. HTTP Status Code:" +
|
||||
response.getStatusLine().getStatusCode() + " Reason:" +
|
||||
response.getStatusLine().getReasonPhrase());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onEntityEnclosed(HttpEntity entity, ContentType contentType) throws IOException
|
||||
{
|
||||
mLog.debug("MyConsumer - onEntityEnclosed()");
|
||||
super.onEntityEnclosed(entity, contentType);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onContentReceived(ContentDecoder decoder, IOControl ioctrl) throws IOException
|
||||
{
|
||||
mLog.debug("MyConsumer - onContentReceived()");
|
||||
super.onContentReceived(decoder, ioctrl);
|
||||
|
||||
mLog.debug("MyConsumer - requesting output from the IO control");
|
||||
ioctrl.requestOutput();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected HttpResponse buildResult(HttpContext context)
|
||||
{
|
||||
mLog.debug("MyConsumer - buildResult()");
|
||||
return super.buildResult(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onClose() throws IOException
|
||||
{
|
||||
mLog.debug("MyConsumer - onClose()");
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Exception getException()
|
||||
{
|
||||
mLog.debug("MyConsumer - getException()");
|
||||
return super.getException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResponse getResult()
|
||||
{
|
||||
mLog.debug("MyConsumer - getResult()");
|
||||
return super.getResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone()
|
||||
{
|
||||
boolean done = super.isDone();
|
||||
|
||||
mLog.debug("MyConsumer - isDone() - super says:" + done);
|
||||
return super.isDone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,9 @@ package audio.broadcast.icecast;
|
||||
public enum IcecastHeader
|
||||
{
|
||||
ACCEPT("Accept"),
|
||||
AUDIO_INFO("ice-audio-info"),
|
||||
AUTHORIZATION("Authorization"),
|
||||
BITRATE("ice-bitrate"),
|
||||
CONTENT_TYPE("Content-Type"),
|
||||
DESCRIPTION("ice-description"),
|
||||
EXPECT("Expect"),
|
||||
|
||||
566
src/audio/broadcast/icecast/IcecastTCPBroadcaster.java
Normal file
566
src/audio/broadcast/icecast/IcecastTCPBroadcaster.java
Normal file
@@ -0,0 +1,566 @@
|
||||
/*******************************************************************************
|
||||
* 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 audio.AudioPacket;
|
||||
import audio.broadcast.BroadcastFormat;
|
||||
import audio.broadcast.BroadcastState;
|
||||
import audio.broadcast.Broadcaster;
|
||||
import audio.broadcast.BroadcastFactory;
|
||||
import audio.convert.IAudioConverter;
|
||||
import controller.ThreadPoolManager;
|
||||
import org.asynchttpclient.BoundRequestBuilder;
|
||||
import org.asynchttpclient.DefaultAsyncHttpClient;
|
||||
import org.asynchttpclient.Realm;
|
||||
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;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class IcecastTCPBroadcaster extends Broadcaster
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger( IcecastTCPBroadcaster.class );
|
||||
private final static String UTF8 = "UTF-8";
|
||||
private final static String TERMINATOR = "\r\n";
|
||||
private final static String SEPARATOR = ":";
|
||||
|
||||
private static final long RECONNECT_INTERVAL_MILLISECONDS = 15000; //15 seconds
|
||||
private long mLastConnectionAttempt = 0;
|
||||
private List<AudioPacket> mPacketsToBroadcast = new ArrayList<>();
|
||||
private AtomicBoolean mConnecting = new AtomicBoolean();
|
||||
private Socket mSocket;
|
||||
private DataOutputStream mOutputStream;
|
||||
private DataInputStream mInputStream;
|
||||
private DefaultAsyncHttpClient mDefaultAsyncHttpClient;
|
||||
|
||||
private int mCounter;
|
||||
|
||||
/**
|
||||
* Creates an Icecast 2.3.2 compatible broadcaster using TCP and a pseudo HTTP 1.0 protocol. This broadcaster is
|
||||
* compatible with Icecast version 2.3.2 and older versions of the server software.
|
||||
*
|
||||
* Note: use @see IcecastHTTPBroadcaster for Icecast version 2.4.x and newer.
|
||||
*
|
||||
* @param configuration
|
||||
* @param audioConverter
|
||||
*/
|
||||
public IcecastTCPBroadcaster(ThreadPoolManager threadPoolManager,
|
||||
IcecastTCPConfiguration configuration,
|
||||
IAudioConverter audioConverter)
|
||||
{
|
||||
super(threadPoolManager, configuration, audioConverter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration information
|
||||
*/
|
||||
private IcecastHTTPConfiguration getConfiguration()
|
||||
{
|
||||
return (IcecastHTTPConfiguration)getBroadcastConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast any queued audio packets using Icecast V2 Protocol
|
||||
*/
|
||||
@Override
|
||||
public void broadcast()
|
||||
{
|
||||
if(connect())
|
||||
{
|
||||
mAudioQueue.drainTo(mPacketsToBroadcast, 5);
|
||||
|
||||
if (!mPacketsToBroadcast.isEmpty())
|
||||
{
|
||||
byte[] convertedAudio = getAudioConverter().convert(mPacketsToBroadcast);
|
||||
|
||||
mLog.debug("We have [" + mPacketsToBroadcast.size() +
|
||||
"] packets - sending:" + convertedAudio.length + " bytes");
|
||||
|
||||
try
|
||||
{
|
||||
send(convertedAudio);
|
||||
}
|
||||
catch(SocketException se)
|
||||
{
|
||||
disconnect();
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
mLog.error("Error sending audio", e);
|
||||
}
|
||||
|
||||
mPacketsToBroadcast.clear();
|
||||
|
||||
mCounter++;
|
||||
|
||||
if(mCounter % 10 == 0)
|
||||
{
|
||||
updateMetadata("Song Count " + mCounter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(canConnect())
|
||||
{
|
||||
createConnection();
|
||||
}
|
||||
|
||||
return connected();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Disconnect from the remote server
|
||||
*/
|
||||
public void disconnect()
|
||||
{
|
||||
if(mOutputStream != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
mOutputStream.flush();
|
||||
mOutputStream.close();
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.debug("Error closing output stream", ioe);
|
||||
}
|
||||
|
||||
mOutputStream = null;
|
||||
}
|
||||
|
||||
if(mInputStream != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
mInputStream.close();
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.debug("Error closing input stream", ioe);
|
||||
}
|
||||
|
||||
mInputStream = null;
|
||||
}
|
||||
|
||||
if(mSocket != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
mSocket.close();
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.error("Error closing socket", ioe);
|
||||
}
|
||||
|
||||
mSocket = null;
|
||||
}
|
||||
|
||||
mLog.debug("Icecast stream is now disconnected");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(mConnecting.compareAndSet(false, true))
|
||||
{
|
||||
if(canConnect() && System.currentTimeMillis() - mLastConnectionAttempt >= RECONNECT_INTERVAL_MILLISECONDS)
|
||||
{
|
||||
mLog.debug("Creating a connection to icecast server");
|
||||
mLastConnectionAttempt = System.currentTimeMillis();
|
||||
|
||||
createSocket();
|
||||
|
||||
if(mSocket.isConnected())
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("SOURCE ").append(getConfiguration().getMountPoint());
|
||||
sb.append(" HTTP/1.0").append(TERMINATOR);
|
||||
|
||||
sb.append("Authorization: ").append(getConfiguration().getEncodedCredentials()).append(TERMINATOR);
|
||||
sb.append(IcecastHeader.USER_AGENT.getValue()).append(SEPARATOR)
|
||||
.append(SystemProperties.getInstance().getApplicationName()).append(TERMINATOR);
|
||||
sb.append(IcecastHeader.CONTENT_TYPE.getValue()).append(SEPARATOR)
|
||||
.append(getConfiguration().getBroadcastFormat().getValue()).append(TERMINATOR);
|
||||
|
||||
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)
|
||||
.append(getConfiguration().getGenre()).append(TERMINATOR);
|
||||
}
|
||||
|
||||
if(getConfiguration().hasDescription())
|
||||
{
|
||||
sb.append(IcecastHeader.DESCRIPTION.getValue()).append(SEPARATOR)
|
||||
.append(getConfiguration().getDescription()).append(TERMINATOR);
|
||||
}
|
||||
|
||||
sb.append(getAudioInfoMetadata());
|
||||
|
||||
sb.append(TERMINATOR).append(TERMINATOR);
|
||||
|
||||
try
|
||||
{
|
||||
mLog.debug("Sending connection string");
|
||||
send(sb.toString());
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
mLog.error("Error while connecting with ...\n" + sb.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
mLog.debug("Checking response ...");
|
||||
checkResponse();
|
||||
}
|
||||
|
||||
mConnecting.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private String getAudioInfoMetadata()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if(getConfiguration().hasBitRate() || getConfiguration().hasChannels() || getConfiguration().hasSampleRate())
|
||||
{
|
||||
sb.append(IcecastHeader.AUDIO_INFO.getValue()).append(SEPARATOR);
|
||||
|
||||
boolean contentAdded = false;
|
||||
|
||||
if(getConfiguration().hasBitRate())
|
||||
{
|
||||
sb.append("bitrate=").append(getConfiguration().getBitRate());
|
||||
contentAdded = true;
|
||||
}
|
||||
if(getConfiguration().hasChannels())
|
||||
{
|
||||
if(contentAdded)
|
||||
{
|
||||
sb.append(";");
|
||||
}
|
||||
|
||||
sb.append("channels=").append(getConfiguration().getChannels());
|
||||
|
||||
contentAdded = true;
|
||||
}
|
||||
if(getConfiguration().hasSampleRate())
|
||||
{
|
||||
if(contentAdded)
|
||||
{
|
||||
sb.append(";");
|
||||
}
|
||||
|
||||
sb.append("samplerate=").append(getConfiguration().getSampleRate());
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(getConfiguration().getHost(),
|
||||
getConfiguration().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[" +
|
||||
getConfiguration().getHost() + "] and port[" +
|
||||
getConfiguration().getPort() + "] - will reattempt connection periodically");
|
||||
return;
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
|
||||
mLog.error("Error connecting to streaming server host[" +
|
||||
getConfiguration().getHost() + "] and port[" +
|
||||
getConfiguration().getPort() + "]", ioe);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(mSocket.isConnected())
|
||||
{
|
||||
setBroadcastState(BroadcastState.CONNECTING);
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
SocketAddress address = getConfiguration().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[" +
|
||||
getConfiguration().getHost() + "] and port[" +
|
||||
getConfiguration().getPort() + "]", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
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
|
||||
{
|
||||
if(connected())
|
||||
{
|
||||
int sent = 0;
|
||||
|
||||
while(sent < data.length)
|
||||
{
|
||||
int available = data.length - sent;
|
||||
|
||||
mOutputStream.write(data, sent, available);
|
||||
|
||||
sent += available;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 void checkResponse()
|
||||
{
|
||||
String response = null;
|
||||
|
||||
try
|
||||
{
|
||||
Thread.sleep(250);
|
||||
|
||||
response = getResponse();
|
||||
}
|
||||
catch(InterruptedException ie)
|
||||
{
|
||||
mLog.debug("Interrupted ...", ie);
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
mLog.error("Error while retrieving server response message", e);
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
|
||||
if(response != null && !response.isEmpty())
|
||||
{
|
||||
if(response.startsWith("HTTP/1.0 200 OK"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.CONNECTED);
|
||||
}
|
||||
else if(response.startsWith("Invalid Password"))
|
||||
{
|
||||
setBroadcastState(BroadcastState.INVALID_PASSWORD);
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.debug("Unrecognized server response:" + response);
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.debug("Response was empty");
|
||||
}
|
||||
}
|
||||
|
||||
private void updateMetadata(String songName)
|
||||
{
|
||||
if(songName != null && !songName.isEmpty())
|
||||
{
|
||||
try
|
||||
{
|
||||
if(mDefaultAsyncHttpClient == null)
|
||||
{
|
||||
mDefaultAsyncHttpClient = new DefaultAsyncHttpClient();
|
||||
}
|
||||
|
||||
String songEncoded = URLEncoder.encode(songName, UTF8);
|
||||
|
||||
StringBuilder query = new StringBuilder();
|
||||
query.append("/admin/metadata?mode=updinfo");
|
||||
query.append("&mount=").append(getConfiguration().getMountPoint());
|
||||
query.append("&charset=UTF%2d8");
|
||||
query.append("&song=").append(songEncoded);
|
||||
|
||||
Uri uri = new Uri(Uri.HTTP, null, getConfiguration().getHost(), getConfiguration().getPort(),
|
||||
query.toString(), null);
|
||||
|
||||
BoundRequestBuilder builder = mDefaultAsyncHttpClient.prepareGet(uri.toUrl());
|
||||
|
||||
//Use Basic (base64) authentication
|
||||
Realm realm = new Realm.Builder(getConfiguration().getUserName(), getConfiguration().getPassword())
|
||||
.setScheme(Realm.AuthScheme.BASIC).setUsePreemptiveAuth(true).build();
|
||||
builder.setRealm(realm);
|
||||
builder.addHeader(IcecastHeader.USER_AGENT.getValue(), SystemProperties.getInstance().getApplicationName());
|
||||
|
||||
mDefaultAsyncHttpClient.executeRequest(builder.build());
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.debug("Error while updating metadata", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
boolean test = false;
|
||||
|
||||
IcecastTCPConfiguration config = new IcecastTCPConfiguration(BroadcastFormat.MP3);
|
||||
|
||||
config.setName("Broadcastify SDRTrunk #2");
|
||||
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);
|
||||
|
||||
if(test)
|
||||
{
|
||||
mLog.debug("Auth:" + config.getEncodedCredentials());
|
||||
}
|
||||
else
|
||||
{
|
||||
ThreadPoolManager threadPoolManager = new ThreadPoolManager();
|
||||
|
||||
final Broadcaster broadcaster = BroadcastFactory.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() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
278
src/audio/broadcast/icecast/IcecastTCPConfiguration.java
Normal file
278
src/audio/broadcast/icecast/IcecastTCPConfiguration.java
Normal file
@@ -0,0 +1,278 @@
|
||||
/*******************************************************************************
|
||||
* 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 audio.broadcast.BroadcastConfiguration;
|
||||
import audio.broadcast.BroadcastFormat;
|
||||
import audio.broadcast.BroadcastServerType;
|
||||
import audio.broadcast.broadcastify.BroadcastifyConfiguration;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlSeeAlso;
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
import java.util.Base64;
|
||||
|
||||
@XmlSeeAlso( {BroadcastifyConfiguration.class } )
|
||||
public class IcecastTCPConfiguration extends BroadcastConfiguration
|
||||
{
|
||||
private String mUserName;
|
||||
private String mMountPoint;
|
||||
private String mDescription;
|
||||
private String mGenre;
|
||||
private boolean mPublic;
|
||||
private int mBitRate;
|
||||
private int mChannels = 1;
|
||||
private int mSampleRate = 8000;
|
||||
private String mURL;
|
||||
|
||||
public IcecastTCPConfiguration()
|
||||
{
|
||||
//No-arg constructor for JAXB
|
||||
}
|
||||
|
||||
/**
|
||||
* Icecast 2.3.x and 2.4.x compatible configuration
|
||||
* @param format
|
||||
*/
|
||||
public IcecastTCPConfiguration(BroadcastFormat format)
|
||||
{
|
||||
super(format);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BroadcastServerType getBroadcastServerType()
|
||||
{
|
||||
return BroadcastServerType.ICECAST_TCP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64 encoded version of the username and password with prepended 'Basic ' tag.
|
||||
*/
|
||||
@XmlTransient
|
||||
public String getEncodedCredentials()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if(hasUserName())
|
||||
{
|
||||
sb.append(getUserName()).append(":").append(getPassword());
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.append(getPassword());
|
||||
}
|
||||
|
||||
String base64 = Base64.getEncoder().encodeToString(sb.toString().getBytes());
|
||||
|
||||
return "Basic " + base64;
|
||||
}
|
||||
|
||||
@XmlAttribute( name="user_name" )
|
||||
public String getUserName()
|
||||
{
|
||||
return mUserName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName)
|
||||
{
|
||||
mUserName = userName;
|
||||
}
|
||||
|
||||
public boolean hasUserName()
|
||||
{
|
||||
return mUserName != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount point or path to the stream
|
||||
* @return mount point
|
||||
*/
|
||||
@XmlAttribute( name="mount_point" )
|
||||
public String getMountPoint()
|
||||
{
|
||||
return mMountPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the mount point (path) for the stream
|
||||
* @param mountPoint
|
||||
*/
|
||||
public void setMountPoint(String mountPoint)
|
||||
{
|
||||
if(mountPoint != null && !mountPoint.isEmpty())
|
||||
{
|
||||
if(mountPoint.startsWith("/"))
|
||||
{
|
||||
mMountPoint = mountPoint;
|
||||
}
|
||||
else
|
||||
{
|
||||
mMountPoint = "/" + mountPoint;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasMountPoint()
|
||||
{
|
||||
return mMountPoint != null;
|
||||
}
|
||||
|
||||
|
||||
@XmlAttribute( name="description" )
|
||||
public String getDescription()
|
||||
{
|
||||
return mDescription;
|
||||
}
|
||||
|
||||
public void setDescription(String description)
|
||||
{
|
||||
mDescription = description;
|
||||
}
|
||||
|
||||
public boolean hasDescription()
|
||||
{
|
||||
return mDescription != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream genre
|
||||
*/
|
||||
@XmlAttribute( name="genre" )
|
||||
public String getGenre()
|
||||
{
|
||||
return mGenre;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream genre
|
||||
* @param genre
|
||||
*/
|
||||
public void setGenre(String genre)
|
||||
{
|
||||
mGenre = genre;
|
||||
}
|
||||
|
||||
public boolean hasGenre()
|
||||
{
|
||||
return mGenre != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public visibility of the broadcast
|
||||
*/
|
||||
@XmlAttribute( name="public" )
|
||||
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
|
||||
*/
|
||||
@XmlAttribute( name="channels" )
|
||||
public int getChannels()
|
||||
{
|
||||
return mChannels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number of audio channels in the broadcast
|
||||
*/
|
||||
public void setChannels(int channels)
|
||||
{
|
||||
mChannels = channels;
|
||||
}
|
||||
|
||||
public boolean hasChannels()
|
||||
{
|
||||
return mChannels > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bit rate in bits per second
|
||||
*/
|
||||
@XmlAttribute( name="bitrate" )
|
||||
public int getBitRate()
|
||||
{
|
||||
return mBitRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bit rate
|
||||
* @param bitRate in samples per second
|
||||
*/
|
||||
public void setBitRate(int bitRate)
|
||||
{
|
||||
mBitRate = bitRate;
|
||||
}
|
||||
|
||||
public boolean hasBitRate()
|
||||
{
|
||||
return mBitRate > 0;
|
||||
}
|
||||
|
||||
@XmlAttribute( name="sample_rate" )
|
||||
public int getSampleRate()
|
||||
{
|
||||
return mSampleRate;
|
||||
}
|
||||
|
||||
public void setSampleRate(int sampleRate)
|
||||
{
|
||||
mSampleRate = sampleRate;
|
||||
}
|
||||
|
||||
public boolean hasSampleRate()
|
||||
{
|
||||
return mSampleRate > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL associated with the broadcast where users can find additional details.
|
||||
*/
|
||||
@XmlAttribute( name="url" )
|
||||
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;
|
||||
}
|
||||
|
||||
public boolean hasURL()
|
||||
{
|
||||
return mURL != null;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* 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 org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.nio.ContentEncoder;
|
||||
import org.apache.http.nio.IOControl;
|
||||
import org.apache.http.nio.entity.HttpAsyncContentProducer;
|
||||
import org.apache.http.nio.protocol.BasicAsyncRequestProducer;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class MyProducer extends BasicAsyncRequestProducer
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger( MyProducer.class );
|
||||
|
||||
public MyProducer(HttpHost target, HttpEntityEnclosingRequest request, HttpAsyncContentProducer producer)
|
||||
{
|
||||
super(target, request, producer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException
|
||||
{
|
||||
// mLog.debug("############### Producing Content");
|
||||
super.produceContent(encoder, ioctrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpRequest generateRequest()
|
||||
{
|
||||
mLog.debug("############### Generating a request");
|
||||
|
||||
HttpRequest request = super.generateRequest();
|
||||
|
||||
mLog.debug("############### Our request class is:" + request.getClass() );
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHost getTarget()
|
||||
{
|
||||
mLog.debug("############### Getting our target");
|
||||
return super.getTarget();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestCompleted(HttpContext context)
|
||||
{
|
||||
mLog.debug("############### requesting completed");
|
||||
super.requestCompleted(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Exception ex)
|
||||
{
|
||||
mLog.debug("############### Fail!");
|
||||
super.failed(ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRepeatable()
|
||||
{
|
||||
mLog.debug("############### Indicating if we're repeatable");
|
||||
return super.isRepeatable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetRequest() throws IOException
|
||||
{
|
||||
mLog.debug("############### resetting request");
|
||||
super.resetRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
mLog.debug("############### Closing");
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user