Compare commits

...

9 Commits

Author SHA1 Message Date
Denny
e430319937 Updates build to 0.3.0 Beta 14 2017-08-19 07:15:57 -04:00
Denny Sheirer
724f769771 Merge pull request #262 from DSheirer/260-icecast-stream-doesn't-reconnect
260 - Icecast and Shoutcast streaming doesn't auto-reconnect
2017-08-19 07:14:55 -04:00
Denny
c196cfebed Resolves issue #260 - applies changes to Shoutcast V1 and v2 that were
applied to the Icecast streamer for issue releated to reconnecting.
2017-08-19 07:13:08 -04:00
Denny
e80b5866d4 Resolves issue #260 where audio streaming was not re-connecting after a
disconnect.
2017-08-18 20:07:53 -04:00
Denny
c8994d5593 Updates build to version 0.3.0 Beta 13 2017-07-22 05:45:36 -04:00
Denny Sheirer
99ef57c90f Merge pull request #255 from DSheirer/249-overflow-teardown-lockup
249 Channel TEARDOWN/OVERFLOW state lockup
2017-07-22 05:44:12 -04:00
Denny
be62ae0459 Resolves #249 - removes the state monitor runnable from the channel
state and replaces it with a processing chain heartbeat that is generated
by the sample source.

Previously, the state monitor was running on a separate thread and this
was causing multi-threading issues.  With this update, all channel state
operations (and all module operations) occur on the source's buffer
processing thread.
2017-07-22 05:42:13 -04:00
Denny Sheirer
b9be6f43e0 Merge pull request #253 from DSheirer/252-usb-transfer-processor-bad-logging
252 USB transfer processor erroneous logging and performance enhancements
2017-07-09 12:29:21 +00:00
Denny
d5ad3f807d Resolves issue where the tuner's buffer processor is logging that an overflow state has been cleared, caused by a clearing of the buffer when the tuner is being shutdown because there are no more channel consumers registered on the tuner.
Tweaked buffer size limits and buffer handling to attempt to avoid overflow situations in the first place.

Resolved an issue where the tuner processor was not deregistering correctly from the LIBUSB tuner processor during tuner shutdown.
2017-07-09 08:21:07 -04:00
17 changed files with 976 additions and 796 deletions

View File

@@ -7,7 +7,7 @@
<property name="major" value="0"/>
<property name="minor" value="3"/>
<property name="patch" value="0"/>
<property name="release" value="-beta12"/>
<property name="release" value="-beta14"/>
<property name="filename" value="sdrtrunk_${major}.${minor}.${patch}${release}"/>
<!-- Build properties -->

View File

@@ -36,6 +36,7 @@ import util.ThreadPool;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.channels.UnresolvedAddressException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -44,7 +45,8 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
private final static Logger mLog = LoggerFactory.getLogger(IcecastTCPAudioBroadcaster.class);
private final static String TERMINATOR = "\r\n";
private final static String SEPARATOR = ":";
private static final long RECONNECT_INTERVAL_MILLISECONDS = 30000; //30 seconds
private static final long RECONNECT_INTERVAL_MILLISECONDS = 3000; //3 seconds
private static final long CONNECTION_ATTEMPT_TIMEOUT = 5000; //5 seconds
private NioSocketConnector mSocketConnector;
private IoSession mStreamingSession = null;
@@ -99,10 +101,11 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
if(mSocketConnector == null)
{
mSocketConnector = new NioSocketConnector();
mSocketConnector.setConnectTimeoutCheckInterval(10000);
mSocketConnector.setConnectTimeoutCheckInterval(CONNECTION_ATTEMPT_TIMEOUT);
// mSocketConnector.getFilterChain().addLast("logger",
// new LoggingFilter(IcecastTCPAudioBroadcaster.class));
// LoggingFilter loggingFilter = new LoggingFilter(IcecastTCPAudioBroadcaster.class);
// loggingFilter.setMessageSentLogLevel(LogLevel.NONE);
// mSocketConnector.getFilterChain().addLast("logger", loggingFilter);
mSocketConnector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new IcecastCodecFactory()));
@@ -123,9 +126,20 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
ConnectFuture future = mSocketConnector
.connect(new InetSocketAddress(getBroadcastConfiguration().getHost(),
getBroadcastConfiguration().getPort()));
future.awaitUninterruptibly();
boolean connected = future.await(CONNECTION_ATTEMPT_TIMEOUT, TimeUnit.MILLISECONDS);
mStreamingSession = future.getSession();
}
catch(UnresolvedAddressException uae)
{
//What do you do with this? Nothing.
}
catch(InterruptedException ie)
{
//We couldn't connect within the timeout period -- disconnect so that we can try again later
disconnect();
}
catch(RuntimeIoException rie)
{
Throwable throwableCause = rie.getCause();
@@ -137,16 +151,20 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
else if(throwableCause != null)
{
setBroadcastState(BroadcastState.ERROR);
mLog.debug("Failed to connect", rie);
mLog.debug("[" + getStreamName() + "] failed to connect", rie);
}
else
{
setBroadcastState(BroadcastState.ERROR);
mLog.debug("Failed to connect - no exception is available");
mLog.debug("[" + getStreamName() + "] failed to connect - no exception is available");
}
disconnect();
}
catch(Throwable t)
{
disconnect();
}
mConnecting.set(false);
}
@@ -164,12 +182,13 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
*/
public void disconnect()
{
if(connected())
{
if(mStreamingSession != null)
if(connected() && mStreamingSession != null)
{
mStreamingSession.closeNow();
}
else
{
mLastConnectionAttempt = System.currentTimeMillis();
}
}
@@ -226,17 +245,18 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
@Override
public void sessionClosed(IoSession session) throws Exception
{
mLastConnectionAttempt = System.currentTimeMillis();
//If there is already an error state, don't override it. Otherwise, set state to disconnected
if(!getBroadcastState().isErrorState())
{
setBroadcastState(BroadcastState.DISCONNECTED);
}
mSocketConnector.dispose();
mStreamingSession = null;
mSocketConnector = null;
mConnecting.set(false);
super.sessionClosed(session);
}
@@ -253,45 +273,36 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
if(connected())
{
mLog.info("Streaming connection error detected - resetting connection - " + reason);
disconnect();
connect();
}
else if(reason.startsWith("Connection reset"))
{
mLog.info("Streaming connection reset by remote server - reestablishing connection");
disconnect();
connect();
}
else if(reason.startsWith("Operation timed out"))
{
mLog.info("Streaming connection timed out - resetting connection");
disconnect();
connect();
}
else
{
setBroadcastState(BroadcastState.ERROR);
disconnect();
mLog.error("Unrecognized IO error: " + reason + ". Streaming halted.", cause);
}
}
else if(ioe instanceof WriteTimeoutException)
{
mLog.info("Network write timeout error - resetting connection");
disconnect();
connect();
}
else
{
setBroadcastState(BroadcastState.ERROR);
disconnect();
mLog.error("Unspecified IO error - streaming halted.", cause);
mLog.error("[" + getStreamName() + "] Unspecified IO error - streaming halted.", cause);
}
}
else
{
mLog.error("Broadcast error", cause);
mLog.error("[" + getStreamName() + "] Broadcast error", cause);
setBroadcastState(BroadcastState.ERROR);
disconnect();
}
@@ -319,6 +330,10 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
{
setBroadcastState(BroadcastState.INVALID_CREDENTIALS);
}
else if(message.contains("HTTP/1.1 501"))
{
disconnect(); //So that we can reconnect later
}
else
{
mLog.error("Unrecognized server response:" + message);
@@ -328,7 +343,7 @@ public class IcecastTCPAudioBroadcaster extends IcecastAudioBroadcaster
}
else
{
mLog.error("Icecast TCP broadcaster - unrecognized message [ " + object.getClass() +
mLog.error("[" + getStreamName() + "]Icecast TCP broadcaster - unrecognized message [ " + object.getClass() +
"] received:" + object.toString());
}
}

View File

@@ -168,6 +168,10 @@ public class ShoutcastV1AudioBroadcaster extends AudioBroadcaster
disconnect();
}
catch(Throwable t)
{
disconnect();
}
mConnecting.set(false);
}
@@ -185,12 +189,13 @@ public class ShoutcastV1AudioBroadcaster extends AudioBroadcaster
*/
public void disconnect()
{
if(connected())
{
if(mStreamingSession != null)
if(connected() && mStreamingSession != null)
{
mStreamingSession.closeNow();
}
else
{
mLastConnectionAttempt = System.currentTimeMillis();
}
}
@@ -226,15 +231,15 @@ public class ShoutcastV1AudioBroadcaster extends AudioBroadcaster
@Override
public void sessionClosed(IoSession session) throws Exception
{
mLastConnectionAttempt = System.currentTimeMillis();
//If there is already an error state, don't override it. Otherwise, set state to disconnected
if(!getBroadcastState().isErrorState())
{
setBroadcastState(BroadcastState.DISCONNECTED);
}
mSocketConnector.dispose();
mStreamingSession = null;
mSocketConnector = null;
mConnecting.set(false);
super.sessionClosed(session);
@@ -255,13 +260,11 @@ public class ShoutcastV1AudioBroadcaster extends AudioBroadcaster
{
mLog.info("Streaming connection reset by remote server - reestablishing connection");
disconnect();
connect();
}
else if(reason.startsWith("Operation timed out"))
{
mLog.info("Streaming connection timed out - resetting connection");
disconnect();
connect();
}
else
{

View File

@@ -204,6 +204,10 @@ public class ShoutcastV2AudioBroadcaster extends AudioBroadcaster implements IBr
disconnect();
}
catch(Throwable t)
{
disconnect();
}
mConnecting.set(false);
}
@@ -221,13 +225,13 @@ public class ShoutcastV2AudioBroadcaster extends AudioBroadcaster implements IBr
*/
public void disconnect()
{
if(connected())
if(connected() && mStreamingSession != null)
{
if(mStreamingSession != null)
{
mStreamingSession.write(new TerminateBroadcast());
mStreamingSession.closeNow();
}
else
{
mLastConnectionAttempt = System.currentTimeMillis();
}
}
@@ -349,15 +353,15 @@ public class ShoutcastV2AudioBroadcaster extends AudioBroadcaster implements IBr
@Override
public void sessionClosed(IoSession session) throws Exception
{
mLastConnectionAttempt = System.currentTimeMillis();
//If there is already an error state, don't override it. Otherwise, set state to disconnected
if(!getBroadcastState().isErrorState())
{
setBroadcastState(BroadcastState.DISCONNECTED);
}
mSocketConnector.dispose();
mStreamingSession = null;
mSocketConnector = null;
mConnecting.set(false);
super.sessionClosed(session);
@@ -378,13 +382,11 @@ public class ShoutcastV2AudioBroadcaster extends AudioBroadcaster implements IBr
{
mLog.info("Streaming connection reset by remote server - reestablishing connection");
disconnect();
connect();
}
else if(reason.startsWith("Operation timed out"))
{
mLog.info("Streaming connection timed out - resetting connection");
disconnect();
connect();
}
else
{

View File

@@ -0,0 +1,31 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 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 channel.heartbeat;
public class Heartbeat
{
/**
* Periodic pulse that is broadcast to subscribing modules within the demodulating chain so that
* monitoring of state and other attributes can occur on the primary demodulation and decoding
* thread.
*/
public Heartbeat()
{
}
}

View File

@@ -0,0 +1,26 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 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 channel.heartbeat;
import sample.Listener;
public interface IHeartbeatListener
{
public Listener<Heartbeat> getHeartbeatListener();
}

View File

@@ -0,0 +1,28 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 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 channel.heartbeat;
import sample.Listener;
public interface IHeartbeatProvider
{
public void setHeartbeatListener(Listener<Heartbeat> listener);
public void removeHeartbeatListener();
}

View File

@@ -20,6 +20,8 @@ package channel.state;
import audio.squelch.ISquelchStateProvider;
import audio.squelch.SquelchState;
import channel.heartbeat.Heartbeat;
import channel.heartbeat.IHeartbeatListener;
import channel.metadata.Attribute;
import channel.metadata.AttributeChangeRequest;
import channel.metadata.IAttributeChangeRequestListener;
@@ -39,16 +41,13 @@ import sample.real.IOverflowListener;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.IFrequencyChangeListener;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static source.tuner.frequency.FrequencyChangeEvent.Event.NOTIFICATION_FREQUENCY_CHANGE;
public class ChannelState extends Module implements ICallEventProvider, IDecoderStateEventListener,
IDecoderStateEventProvider, IFrequencyChangeListener, ISquelchStateProvider, IAttributeChangeRequestListener,
IOverflowListener
IDecoderStateEventProvider, IFrequencyChangeListener, IHeartbeatListener, ISquelchStateProvider,
IAttributeChangeRequestListener, IOverflowListener
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelState.class);
@@ -61,8 +60,7 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
private Listener<DecoderStateEvent> mDecoderStateListener;
private Listener<SquelchState> mSquelchStateListener;
private DecoderStateEventReceiver mDecoderStateEventReceiver = new DecoderStateEventReceiver();
private StateMonitor mStateMonitor = new StateMonitor();
private ScheduledFuture<?> mStateMonitorFuture;
private HeartbeatReceiver mHeartbeatReceiver = new HeartbeatReceiver();
private ChannelType mChannelType;
private TrafficChannelManager mTrafficChannelEndListener;
private CallEvent mTrafficChannelCallEvent;
@@ -79,30 +77,21 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
/**
* Channel state tracks the overall state of all processing modules and decoders
* configured for the channel and provides squelch control and decoder state
* reset events.
* Channel state tracks the overall state of all processing modules and decoders configured for the channel and
* provides squelch control and decoder state reset events.
*
* Uses a state enumeration that defines allowable channel state transitions in
* order to track a call or data decode event from start to finish. Uses a
* timer to monitor for inactivity and to provide a FADE period that indicates
* to the user that the activity has stopped while continuing to provide details
* about the call, before the state is reset to IDLE.
*
* Since this class is multi-threaded between decoder events and the internal
* timer that monitors for inactivity, this class uses the mState object for
* thread synchronization.
* Uses a state enumeration that defines allowable channel state transitions in order to track a call or data decode
* event from start to finish. Uses a timer to monitor for inactivity and to provide a FADE period that indicates
* to the user that the activity has stopped while continuing to provide details about the call, before the state is
* reset to IDLE.
*
* State Descriptions:
* IDLE Normal state. No voice or data call activity
* CALL/DATA/ENCRYPTED/CONTROL
* Decoding states.
* FADE The phase after a voice or data call when either an explicit
* call end has been received, or when no new signalling updates
* have been received, and the fade timer has expired. This phase
* allows for gui updates to signal to the user that the call is
* ended, while continuing to display the call details for the user
* TEARDOWN Indicates a traffic channel that will be torn down for reuse.
* IDLE: Normal state. No voice or data call activity
* CALL/DATA/ENCRYPTED/CONTROL: Decoding states.
* FADE: The phase after a voice or data call when either an explicit call end has been received, or when no new
* signalling updates have been received, and the fade timer has expired. This phase allows for gui updates to
* signal to the user that the call is ended, while continuing to display the call details for the user
* TEARDOWN: Indicates a traffic channel that will be torn down for reuse.
*/
public ChannelState(ChannelType channelType)
{
@@ -136,8 +125,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
@Override
public void start(ScheduledExecutorService executor)
{
if(mStateMonitorFuture == null && mStateMonitor != null)
{
mMutableMetadata.receive(new AttributeChangeRequest<State>(Attribute.CHANNEL_STATE, mState));
@@ -145,16 +132,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
{
setState(State.CALL);
}
try
{
mStateMonitorFuture = executor.scheduleAtFixedRate(mStateMonitor, 0, 20, TimeUnit.MILLISECONDS);
}
catch(RejectedExecutionException ree)
{
mLog.error("state monitor scheduled task rejected", ree);
}
}
}
@Override
@@ -162,16 +139,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
{
mMutableMetadata.resetAllAttributes();
if(mStateMonitorFuture != null)
{
boolean success = mStateMonitorFuture.cancel(true);
if(!success)
{
mLog.error("Couldn't stop monitoring scheduled future");
}
}
mTrafficChannelEndListener = null;
if(mTrafficChannelCallEvent != null)
@@ -182,8 +149,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
mTrafficChannelCallEvent = null;
mStateMonitorFuture = null;
mSquelchLocked = false;
}
@@ -192,7 +157,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
mCallEventListener = null;
mDecoderStateListener = null;
mSquelchStateListener = null;
mStateMonitor = null;
}
@Override
@@ -312,15 +276,12 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
}
/**
* Sets the channel state to the specified state, or updates the timeout
* values so that the state monitor will not change state. Broadcasts a
* squelch event when the state changes and the audio squelch state should
* change. Also broadcasts changed attribute and decoder state events so
* that external processes can maintain sync with this channel state.
* Sets the channel state to the specified state, or updates the timeout values so that the state monitor will not
* change state. Broadcasts a squelch event when the state changes and the audio squelch state should change. Also
* broadcasts changed attribute and decoder state events so that external processes can maintain sync with this
* channel state.
*/
protected void setState(State state)
{
synchronized(mState)
{
if(state == mState)
{
@@ -329,13 +290,12 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
updateFadeTimeout();
}
}
else if(state != mState && mState.canChangeTo(state))
else if(mState.canChangeTo(state))
{
switch(state)
{
case CONTROL:
//Don't allow traffic channels to be control channels,
//otherwise they can't transition to call tear down
//Don't allow traffic channels to be control channels, otherwise they can't transition to teardown
if(isStandardChannel())
{
broadcast(SquelchState.SQUELCH);
@@ -374,6 +334,14 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
mSourceOverflow ? State.OVERFLOW : mState));
}
}
/**
* Receiver inner class that implements the IHeartbeatListener interface to receive heartbeat messages.
*/
@Override
public Listener<Heartbeat> getHeartbeatListener()
{
return mHeartbeatReceiver;
}
/**
@@ -625,30 +593,27 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
}
/**
* Monitors decoder state events to automatically transition the channel
* state to IDLE (standard channel) or to TEARDOWN (traffic channel) when
* decoding stops or the monitored channel returns to a no signal state.
* Processes periodic heartbeats received from the processing chain to perform state monitoring and cleanup
* functions.
*
* Provides a FADE transition state to allow for momentary decoding dropouts
* and to allow the user access to call details for a fade period upon
* call end.
* Monitors decoder state events to automatically transition the channel state to IDLE (standard channel) or to
* TEARDOWN (traffic channel) when decoding stops or the monitored channel returns to a no signal state.
*
* Provides a FADE transition state to allow for momentary decoding dropouts and to allow the user access to call
* details for a fade period upon call end.
*/
public class StateMonitor implements Runnable
public class HeartbeatReceiver implements Listener<Heartbeat>
{
@Override
public void run()
public void receive(Heartbeat heartbeat)
{
try
{
synchronized(mState)
{
if(State.CALL_STATES.contains(mState) &&
mFadeTimeout <= System.currentTimeMillis())
if(State.CALL_STATES.contains(mState) && mFadeTimeout <= System.currentTimeMillis())
{
processFadeState();
}
else if(mState == State.FADE &&
mEndTimeout <= System.currentTimeMillis())
else if(mState == State.FADE && mEndTimeout <= System.currentTimeMillis())
{
if(isTrafficChannel())
{
@@ -660,7 +625,6 @@ public class ChannelState extends Module implements ICallEventProvider, IDecoder
}
}
}
}
catch(Throwable e)
{
mLog.error("An error occurred while state monitor was running " +

View File

@@ -24,16 +24,17 @@ import audio.IAudioPacketProvider;
import audio.squelch.ISquelchStateListener;
import audio.squelch.ISquelchStateProvider;
import audio.squelch.SquelchState;
import channel.heartbeat.Heartbeat;
import channel.heartbeat.IHeartbeatListener;
import channel.heartbeat.IHeartbeatProvider;
import channel.metadata.AttributeChangeRequest;
import channel.metadata.IAttributeChangeRequestListener;
import channel.metadata.IAttributeChangeRequestProvider;
import channel.state.ChannelState;
import channel.state.DecoderState;
import channel.state.DecoderStateEvent;
import channel.state.DecoderStateEvent.Event;
import channel.state.IDecoderStateEventListener;
import channel.state.IDecoderStateEventProvider;
import channel.state.State;
import controller.channel.Channel.ChannelType;
import controller.channel.ChannelEvent;
import controller.channel.IChannelEventListener;
@@ -63,8 +64,6 @@ import sample.real.RealBuffer;
import source.ComplexSource;
import source.RealSource;
import source.Source;
import source.SourceException;
import source.tuner.TunerChannelSource;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.IFrequencyChangeListener;
import source.tuner.frequency.IFrequencyChangeProvider;
@@ -103,6 +102,7 @@ public class ProcessingChain implements IChannelEventListener
private Broadcaster<ComplexBuffer> mComplexBufferBroadcaster = new Broadcaster<>();
private Broadcaster<DecoderStateEvent> mDecoderStateEventBroadcaster = new Broadcaster<>();
private Broadcaster<FrequencyChangeEvent> mFrequencyChangeEventBroadcaster = new Broadcaster<>();
private Broadcaster<Heartbeat> mHeartbeatBroadcaster = new Broadcaster<>();
private Broadcaster<Message> mMessageBroadcaster = new Broadcaster<>();
private Broadcaster<RealBuffer> mFilteredRealBufferBroadcaster = new Broadcaster<>();
private Broadcaster<RealBuffer> mUnFilteredRealBufferBroadcaster = new Broadcaster<>();
@@ -329,6 +329,11 @@ public class ProcessingChain implements IChannelEventListener
}
}
if(module instanceof IHeartbeatListener)
{
mHeartbeatBroadcaster.addListener(((IHeartbeatListener)module).getHeartbeatListener());
}
if(module instanceof IMessageListener)
{
mMessageBroadcaster.addListener(((IMessageListener) module).getMessageListener());
@@ -391,6 +396,11 @@ public class ProcessingChain implements IChannelEventListener
mFrequencyChangeEventBroadcaster.removeListener(((IFrequencyChangeListener) module).getFrequencyChangeListener());
}
if(module instanceof IHeartbeatListener)
{
mHeartbeatBroadcaster.removeListener(((IHeartbeatListener)module).getHeartbeatListener());
}
if(module instanceof IMessageListener)
{
mMessageBroadcaster.removeListener(((IMessageListener) module).getMessageListener());
@@ -448,6 +458,11 @@ public class ProcessingChain implements IChannelEventListener
((IFrequencyChangeProvider) module).setFrequencyChangeListener(mFrequencyChangeEventBroadcaster);
}
if(module instanceof IHeartbeatProvider)
{
((IHeartbeatProvider)module).setHeartbeatListener(mHeartbeatBroadcaster);
}
if(module instanceof IMessageProvider)
{
((IMessageProvider) module).setMessageListener(mMessageBroadcaster);
@@ -505,6 +520,11 @@ public class ProcessingChain implements IChannelEventListener
((IFrequencyChangeProvider) module).setFrequencyChangeListener(null);
}
if(module instanceof IHeartbeatProvider)
{
((IHeartbeatProvider)module).removeHeartbeatListener();
}
if(module instanceof IMessageProvider)
{
((IMessageProvider) module).setMessageListener(null);

View File

@@ -1713,6 +1713,8 @@ public class P25DecoderState extends DecoderState
.build());
break;
case SNDCP_RF_CONFIRMED_DATA:
if(pduc instanceof SNDCPUserData)
{
SNDCPUserData sud = (SNDCPUserData)pduc;
StringBuilder sbFrom = new StringBuilder();
@@ -1740,6 +1742,12 @@ public class P25DecoderState extends DecoderState
.from(sbFrom.toString())
.to(pduc.getLogicalLinkID())
.build());
}
else
{
mLog.error("Error - expected SNDCPUserData instance but class was: " + pduc.getClass() +
" and PDU Type:" + pduc.getPDUType().name());
}
break;
case SNDCP_RF_UNCONFIRMED_DATA:
break;

View File

@@ -124,10 +124,6 @@ public class OverflowableTransferQueue<E>
mQueue.clear();
mCounter.set(0);
mOverflow.set(false);
if(mOverflowListener != null)
{
mOverflowListener.sourceOverflow(false);
}
}
}
}

View File

@@ -17,6 +17,7 @@
******************************************************************************/
package source;
import channel.heartbeat.IHeartbeatProvider;
import module.Module;
import sample.SampleType;
import sample.real.IOverflowListener;
@@ -26,7 +27,8 @@ import source.tuner.frequency.IFrequencyChangeProvider;
/**
* Abstract class to define the minimum functionality of a sample data provider.
*/
public abstract class Source extends Module implements IFrequencyChangeListener, IFrequencyChangeProvider
public abstract class Source extends Module implements IFrequencyChangeListener, IFrequencyChangeProvider,
IHeartbeatProvider
{
protected SampleType mSampleType;
protected IOverflowListener mOverflowListener;

View File

@@ -17,30 +17,29 @@
******************************************************************************/
package source.mixer;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import channel.heartbeat.Heartbeat;
import dsp.gain.AutomaticGainControl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.adapter.ISampleAdapter;
import sample.real.RealBuffer;
import source.RealSource;
import source.SourceException;
import dsp.gain.AutomaticGainControl;
import source.tuner.frequency.FrequencyChangeEvent;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
public class RealMixerSource extends RealSource
{
private final static Logger mLog = LoggerFactory.getLogger( RealMixerSource.class );
private final static Logger mLog = LoggerFactory.getLogger(RealMixerSource.class);
private long mFrequency = 0;
private int mBufferSize = 16384;
@@ -51,8 +50,10 @@ public class RealMixerSource extends RealSource
private int mBytesPerFrame = 0;
private ISampleAdapter mSampleAdapter;
private AutomaticGainControl mAGC = new AutomaticGainControl();
private Listener<Heartbeat> mHeartbeatListener;
private static final Heartbeat HEARTBEAT = new Heartbeat();
CopyOnWriteArrayList<Listener<RealBuffer>> mSampleListeners = new CopyOnWriteArrayList<Listener<RealBuffer>>();
private CopyOnWriteArrayList<Listener<RealBuffer>> mSampleListeners = new CopyOnWriteArrayList<Listener<RealBuffer>>();
/**
* Real Mixer Source - constructs a reader on the mixer/sound card target
@@ -61,18 +62,14 @@ public class RealMixerSource extends RealSource
* Reads buffers sized to 10% of the sample rate specified in audio format.
*
* @param targetDataLine - mixer or sound card to be used
*
* @param format - audio format
*
* @param name - token name to use for this source
*
* @param sampleAdapter - adapter to convert byte array data read from the
* mixer into float array data. Can optionally invert the channel data if
* the left/right stereo channels are inverted.
*/
public RealMixerSource( TargetDataLine targetDataLine,
public RealMixerSource(TargetDataLine targetDataLine,
AudioFormat format,
ISampleAdapter sampleAdapter )
ISampleAdapter sampleAdapter)
{
mTargetDataLine = targetDataLine;
mAudioFormat = format;
@@ -98,13 +95,33 @@ public class RealMixerSource extends RealSource
return null;
}
/**
* Registers the listener to receive heartbeats from this source.
*
* @param listener to receive heartbeats
*/
@Override
public void setHeartbeatListener(Listener<Heartbeat> listener)
{
mHeartbeatListener = listener;
}
/**
* Removes the currently registered heartbeat listener
*/
@Override
public void removeHeartbeatListener()
{
mHeartbeatListener = null;
}
@Override
public void reset()
{
}
@Override
public void start( ScheduledExecutorService executor )
public void start(ScheduledExecutorService executor)
{
}
@@ -113,55 +130,55 @@ public class RealMixerSource extends RealSource
{
}
public void setListener( Listener<RealBuffer> listener )
public void setListener(Listener<RealBuffer> listener)
{
mSampleListeners.add( listener );
mSampleListeners.add(listener);
/* If this is the first listener, start the reader thread */
if( !mBufferReader.isRunning() )
if(!mBufferReader.isRunning())
{
Thread thread = new Thread( mBufferReader );
thread.setDaemon( true );
thread.setName( "Sample Reader" );
Thread thread = new Thread(mBufferReader);
thread.setDaemon(true);
thread.setName("Sample Reader");
thread.start();
}
}
public void removeListener( Listener<RealBuffer> listener )
public void removeListener(Listener<RealBuffer> listener)
{
mSampleListeners.remove( listener );
mSampleListeners.remove(listener);
/* If this is the laster listener, stop the reader thread */
if( mSampleListeners.isEmpty() )
if(mSampleListeners.isEmpty())
{
mBufferReader.stop();
}
}
public void broadcast( RealBuffer samples )
public void broadcast(RealBuffer samples)
{
Iterator<Listener<RealBuffer>> it = mSampleListeners.iterator();
while( it.hasNext() )
while(it.hasNext())
{
Listener<RealBuffer> next = it.next();
/* if this is the last (or only) listener, send him the original
* buffer, otherwise send him a copy of the buffer */
if( it.hasNext() )
if(it.hasNext())
{
next.receive( samples.copyOf() );
next.receive(samples.copyOf());
}
else
{
next.receive( samples );
next.receive(samples);
}
}
}
public int getSampleRate()
{
if( mTargetDataLine != null )
if(mTargetDataLine != null)
{
return (int)mTargetDataLine.getFormat().getSampleRate();
}
@@ -184,7 +201,7 @@ public class RealMixerSource extends RealSource
* be useful if you are streaming an external audio source in through the
* sound card and you want to specify a frequency for that source
*/
public void setFrequency( long frequency )
public void setFrequency(long frequency)
{
mFrequency = frequency;
}
@@ -201,71 +218,77 @@ public class RealMixerSource extends RealSource
@Override
public void run()
{
if( mRunning.compareAndSet( false, true ) )
if(mRunning.compareAndSet(false, true))
{
if( mTargetDataLine == null )
//Send a heartbeat every time we run
if(mHeartbeatListener != null)
{
mRunning.set( false );
mHeartbeatListener.receive(HEARTBEAT);
}
mLog.error( "ComplexMixerSource - mixer target data line"
+ " is null" );
if(mTargetDataLine == null)
{
mRunning.set(false);
mLog.error("ComplexMixerSource - mixer target data line"
+ " is null");
}
else
{
mBytesPerFrame = mAudioFormat.getSampleSizeInBits() / 8;
if( mBytesPerFrame == AudioSystem.NOT_SPECIFIED )
if(mBytesPerFrame == AudioSystem.NOT_SPECIFIED)
{
mBytesPerFrame = 2;
}
/* Set buffer size to 1/10 second of samples */
mBufferSize = (int)( mAudioFormat.getSampleRate()
* 0.05 ) * mBytesPerFrame;
mBufferSize = (int)(mAudioFormat.getSampleRate()
* 0.05) * mBytesPerFrame;
/* We'll reuse the same buffer for each read */
byte[] buffer = new byte[ mBufferSize ];
byte[] buffer = new byte[mBufferSize];
try
{
mTargetDataLine.open( mAudioFormat );
mTargetDataLine.open(mAudioFormat);
mTargetDataLine.start();
}
catch ( LineUnavailableException e )
catch(LineUnavailableException e)
{
mLog.error( "ComplexMixerSource - mixer target data line"
+ "not available to read data from", e );
mLog.error("ComplexMixerSource - mixer target data line"
+ "not available to read data from", e);
mRunning.set( false );
mRunning.set(false);
}
while( mRunning.get() )
while(mRunning.get())
{
try
{
/* Blocking read - waits until the buffer fills */
mTargetDataLine.read( buffer, 0, buffer.length );
mTargetDataLine.read(buffer, 0, buffer.length);
/* Convert samples to float array */
float[] samples =
mSampleAdapter.convert( buffer );
mSampleAdapter.convert(buffer);
/* Dispatch samples to registered listeners */
broadcast( new RealBuffer( samples ) );
broadcast(new RealBuffer(samples));
}
catch ( Exception e )
catch(Exception e)
{
mLog.error( "ComplexMixerSource - error while reading"
+ "from the mixer target data line", e );
mLog.error("ComplexMixerSource - error while reading"
+ "from the mixer target data line", e);
mRunning.set( false );
mRunning.set(false);
}
}
}
/* Close the data line if it is still open */
if( mTargetDataLine != null && mTargetDataLine.isOpen() )
if(mTargetDataLine != null && mTargetDataLine.isOpen())
{
mTargetDataLine.close();
}
@@ -277,7 +300,7 @@ public class RealMixerSource extends RealSource
*/
public void stop()
{
if( mRunning.compareAndSet( true, false ) )
if(mRunning.compareAndSet(true, false))
{
mTargetDataLine.stop();
mTargetDataLine.close();
@@ -296,7 +319,7 @@ public class RealMixerSource extends RealSource
@Override
public void dispose()
{
if( mBufferReader != null )
if(mBufferReader != null)
{
mBufferReader.stop();
mSampleListeners.clear();

View File

@@ -18,6 +18,8 @@
******************************************************************************/
package source.tuner;
import channel.heartbeat.Heartbeat;
import channel.heartbeat.IHeartbeatProvider;
import dsp.filter.FilterFactory;
import dsp.filter.Window.WindowType;
import dsp.filter.cic.ComplexPrimeCICDecimate;
@@ -58,6 +60,7 @@ public class TunerChannelSource extends ComplexSource implements IFrequencyChang
private static int CHANNEL_RATE = 48000;
private static int CHANNEL_PASS_FREQUENCY = 12000;
private static final Heartbeat HEARTBEAT = new Heartbeat();
private OverflowableTransferQueue<ComplexBuffer> mBuffer;
@@ -66,6 +69,7 @@ public class TunerChannelSource extends ComplexSource implements IFrequencyChang
private Oscillator mMixer;
private ComplexPrimeCICDecimate mDecimationFilter;
private Listener<ComplexBuffer> mListener;
private Listener<Heartbeat> mHeartbeatListener;
private IFrequencyChangeProcessor mFrequencyChangeProcessor;
private DownstreamProcessor mDownstreamFrequencyEventProcessor = new DownstreamProcessor();
private ScheduledFuture<?> mTaskHandle;
@@ -352,6 +356,25 @@ public class TunerChannelSource extends ComplexSource implements IFrequencyChang
return mDownstreamFrequencyEventProcessor.getFrequencyChangeListener();
}
/**
* Registers the listener to receive heartbeats from this source.
* @param listener to receive heartbeats
*/
@Override
public void setHeartbeatListener(Listener<Heartbeat> listener)
{
mHeartbeatListener = listener;
}
/**
* Removes the currently registered heartbeat listener
*/
@Override
public void removeHeartbeatListener()
{
mHeartbeatListener = null;
}
/**
* Managers frequency change requests and notifications from/to any downstream component. Downstream
* components are those that receive samples from this tuner channel source. These downstream components will be
@@ -477,6 +500,13 @@ public class TunerChannelSource extends ComplexSource implements IFrequencyChang
{
if(mProcessing)
{
//Send a heartbeat every time this runs to allow downstream components to perform periodic
//state monitoring functions on this thread
if(mHeartbeatListener != null)
{
mHeartbeatListener.receive(HEARTBEAT);
}
mBuffer.drainTo(mSampleBuffers, 20);
for(Buffer buffer : mSampleBuffers)

View File

@@ -54,7 +54,7 @@ public class USBTransferProcessor implements TransferCallback
private static final int TRANSFER_BUFFER_POOL_SIZE = 16;
//Maximum number of filled buffers for the blocking queue
private static final int FILLED_BUFFER_MAX_CAPACITY = 300;
private static final int FILLED_BUFFER_MAX_CAPACITY = 500;
//Threshold for resetting buffer overflow condition
private static final int FILLED_BUFFER_OVERFLOW_RESET_THRESHOLD = 100;
@@ -200,7 +200,7 @@ public class USBTransferProcessor implements TransferCallback
//Unregister from LibUSB processor so that it auto-stops LibUSB processing
TunerManager.LIBUSB_TRANSFER_PROCESSOR.registerTransferProcessor(this);
TunerManager.LIBUSB_TRANSFER_PROCESSOR.unregisterTransferProcessor(this);
//Directly invoke the timeout handler to ensure that our cancelled transfer buffers are flushed.
int result = LibUsb.handleEventsTimeoutCompleted(null, USB_TIMEOUT_MS,
@@ -414,11 +414,13 @@ public class USBTransferProcessor implements TransferCallback
@Override
public void run()
{
mFilledBuffers.drainTo(mBuffersToDispatch, 50);
while(!mBuffersToDispatch.isEmpty())
{
try
{
mFilledBuffers.drainTo(mBuffersToDispatch, 15);
for(byte[] buffer : mBuffersToDispatch)
{
float[] complexSamples = mSampleAdapter.convert(buffer);
@@ -432,6 +434,8 @@ public class USBTransferProcessor implements TransferCallback
}
mBuffersToDispatch.clear();
mFilledBuffers.drainTo(mBuffersToDispatch, 50);
}
}
}
}

View File

@@ -18,19 +18,9 @@
******************************************************************************/
package source.wave;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import channel.heartbeat.Heartbeat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.ConversionUtils;
import sample.Listener;
import sample.complex.ComplexBuffer;
@@ -39,10 +29,19 @@ import source.IControllableFileSource;
import source.IFrameLocationListener;
import source.tuner.frequency.FrequencyChangeEvent;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
public class ComplexWaveSource extends ComplexSource implements IControllableFileSource
{
private final static Logger mLog =
LoggerFactory.getLogger( ComplexWaveSource.class );
LoggerFactory.getLogger(ComplexWaveSource.class);
private IFrameLocationListener mFrameLocationListener;
private int mBytesPerFrame;
@@ -52,7 +51,7 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
private AudioInputStream mInputStream;
private File mFile;
public ComplexWaveSource( File file ) throws IOException
public ComplexWaveSource(File file) throws IOException
{
mFile = file;
}
@@ -76,23 +75,39 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
return null;
}
/**
* Not implemented
*/
@Override
public void setHeartbeatListener(Listener<Heartbeat> listener)
{
}
/**
* Not implemented
*/
@Override
public void removeHeartbeatListener()
{
}
@Override
public void reset()
{
stop();
start( null );
start(null);
}
@Override
public void start( ScheduledExecutorService executor )
public void start(ScheduledExecutorService executor)
{
try
{
open();
}
catch ( IOException | UnsupportedAudioFileException e )
catch(IOException | UnsupportedAudioFileException e)
{
mLog.error( "Error starting complex wave source" );
mLog.error("Error starting complex wave source");
}
}
@@ -103,9 +118,9 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
{
close();
}
catch ( IOException e )
catch(IOException e)
{
mLog.error( "Error stopping complex wave source" );
mLog.error("Error stopping complex wave source");
}
}
@@ -119,7 +134,7 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
@Override
public int getSampleRate()
{
if( mInputStream != null )
if(mInputStream != null)
{
return (int)mInputStream.getFormat().getSampleRate();
}
@@ -139,7 +154,7 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
/**
* Changes the value returned from getFrequency() for this source.
*/
public void setFrequency( long frequency )
public void setFrequency(long frequency)
{
mFrequency = frequency;
}
@@ -149,13 +164,13 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
*/
public void close() throws IOException
{
if( mInputStream != null )
if(mInputStream != null)
{
mInputStream.close();
}
else
{
throw new IOException( "Can't close wave source - was not opened" );
throw new IOException("Can't close wave source - was not opened");
}
mInputStream = null;
@@ -166,13 +181,13 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
*/
public void open() throws IOException, UnsupportedAudioFileException
{
if( mInputStream == null )
if(mInputStream == null)
{
mInputStream = AudioSystem.getAudioInputStream( mFile );
mInputStream = AudioSystem.getAudioInputStream(mFile);
}
else
{
throw new IOException( "Can't open wave source - is already opened" );
throw new IOException("Can't open wave source - is already opened");
}
@@ -180,54 +195,54 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
mBytesPerFrame = format.getFrameSize();
if( format.getChannels() != 2 || format.getSampleSizeInBits() != 16 )
if(format.getChannels() != 2 || format.getSampleSizeInBits() != 16)
{
throw new IOException( "Unsupported Wave Format - EXPECTED: 2 " +
throw new IOException("Unsupported Wave Format - EXPECTED: 2 " +
"channels 16-bit samples FOUND: " +
mInputStream.getFormat().getChannels() + " channels " +
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples" );
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples");
}
/* Broadcast that we're at frame location 0 */
broadcast( 0 );
broadcast(0);
}
/**
* Reads the number of frames and sends a buffer to the listener
*/
@Override
public void next( int frames ) throws IOException
public void next(int frames) throws IOException
{
next( frames, true );
next(frames, true);
}
/**
* Reads the number of frames and optionally sends the buffer to the listener
*/
public void next( int frames, boolean broadcast ) throws IOException
public void next(int frames, boolean broadcast) throws IOException
{
if( mInputStream != null )
if(mInputStream != null)
{
byte[] buffer = new byte[ mBytesPerFrame * frames ];
byte[] buffer = new byte[mBytesPerFrame * frames];
/* Fill the buffer with samples from the file */
int samplesRead = mInputStream.read( buffer );
int samplesRead = mInputStream.read(buffer);
mFrameCounter += samplesRead;
broadcast( mFrameCounter );
broadcast(mFrameCounter);
if( broadcast && mListener != null )
if(broadcast && mListener != null)
{
if( samplesRead < buffer.length )
if(samplesRead < buffer.length)
{
buffer = Arrays.copyOf( buffer, samplesRead );
buffer = Arrays.copyOf(buffer, samplesRead);
}
float[] samples = ConversionUtils
.convertFromSigned16BitSamples( buffer );
.convertFromSigned16BitSamples(buffer);
mListener.receive( new ComplexBuffer( samples ) );
mListener.receive(new ComplexBuffer(samples));
}
}
}
@@ -237,7 +252,7 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
* the wave file
*/
@Override
public void setListener( Listener<ComplexBuffer> listener )
public void setListener(Listener<ComplexBuffer> listener)
{
mListener = listener;
}
@@ -245,7 +260,7 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
/**
* Unregisters the listener from receiving sample buffers
*/
public void removeListener( Listener<ComplexBuffer> listener )
public void removeListener(Listener<ComplexBuffer> listener)
{
mListener = null;
}
@@ -262,24 +277,24 @@ public class ComplexWaveSource extends ComplexSource implements IControllableFil
return mFile;
}
private void broadcast( int byteLocation )
private void broadcast(int byteLocation)
{
int frameLocation = (int)( byteLocation / mBytesPerFrame );
int frameLocation = (int)(byteLocation / mBytesPerFrame);
if( mFrameLocationListener != null )
if(mFrameLocationListener != null)
{
mFrameLocationListener.frameLocationUpdated( frameLocation );
mFrameLocationListener.frameLocationUpdated(frameLocation);
}
}
@Override
public void setListener( IFrameLocationListener listener )
public void setListener(IFrameLocationListener listener)
{
mFrameLocationListener = listener;
}
@Override
public void removeListener( IFrameLocationListener listener )
public void removeListener(IFrameLocationListener listener)
{
mFrameLocationListener = null;
}

View File

@@ -17,19 +17,9 @@
******************************************************************************/
package source.wave;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import channel.heartbeat.Heartbeat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.ConversionUtils;
import sample.Listener;
import sample.real.RealBuffer;
@@ -38,11 +28,18 @@ import source.IFrameLocationListener;
import source.RealSource;
import source.tuner.frequency.FrequencyChangeEvent;
public class RealWaveSource extends RealSource
implements IControllableFileSource, AutoCloseable
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
public class RealWaveSource extends RealSource implements IControllableFileSource, AutoCloseable
{
private final static Logger mLog =
LoggerFactory.getLogger( RealWaveSource.class );
private final static Logger mLog = LoggerFactory.getLogger(RealWaveSource.class);
private IFrameLocationListener mFrameLocationListener;
private int mBytesPerFrame;
@@ -52,7 +49,7 @@ public class RealWaveSource extends RealSource
private AudioInputStream mInputStream;
private File mFile;
public RealWaveSource( File file ) throws IOException
public RealWaveSource(File file) throws IOException
{
mFile = file;
}
@@ -76,25 +73,41 @@ public class RealWaveSource extends RealSource
return null;
}
/**
* Not implemented
*/
@Override
public void setHeartbeatListener(Listener<Heartbeat> listener)
{
}
/**
* Not implemented
*/
@Override
public void removeHeartbeatListener()
{
}
@Override
public void reset()
{
stop();
start( null );
start(null);
}
@Override
public void start( ScheduledExecutorService executor )
public void start(ScheduledExecutorService executor)
{
try
{
open();
}
catch ( IOException | UnsupportedAudioFileException e )
catch(IOException | UnsupportedAudioFileException e)
{
mLog.error( "Error starting real wave source", e );
mLog.error("Error starting real wave source", e);
}
}
@@ -106,9 +119,9 @@ public class RealWaveSource extends RealSource
{
close();
}
catch ( IOException e )
catch(IOException e)
{
mLog.error( "Error stopping real wave source", e );
mLog.error("Error stopping real wave source", e);
}
}
@@ -123,7 +136,7 @@ public class RealWaveSource extends RealSource
@Override
public int getSampleRate()
{
if( mInputStream != null )
if(mInputStream != null)
{
return (int)mInputStream.getFormat().getSampleRate();
}
@@ -143,7 +156,7 @@ public class RealWaveSource extends RealSource
/**
* Changes the value returned from getFrequency() for this source.
*/
public void setFrequency( long frequency )
public void setFrequency(long frequency)
{
mFrequency = frequency;
}
@@ -153,13 +166,13 @@ public class RealWaveSource extends RealSource
*/
public void close() throws IOException
{
if( mInputStream != null )
if(mInputStream != null)
{
mInputStream.close();
}
else
{
throw new IOException( "Can't close wave source - was not opened" );
throw new IOException("Can't close wave source - was not opened");
}
mInputStream = null;
@@ -170,13 +183,13 @@ public class RealWaveSource extends RealSource
*/
public void open() throws IOException, UnsupportedAudioFileException
{
if( mInputStream == null )
if(mInputStream == null)
{
mInputStream = AudioSystem.getAudioInputStream( mFile );
mInputStream = AudioSystem.getAudioInputStream(mFile);
}
else
{
throw new IOException( "Can't open wave source - is already opened" );
throw new IOException("Can't open wave source - is already opened");
}
@@ -184,59 +197,59 @@ public class RealWaveSource extends RealSource
mBytesPerFrame = format.getFrameSize();
if( format.getChannels() != 1 || format.getSampleSizeInBits() != 16 )
if(format.getChannels() != 1 || format.getSampleSizeInBits() != 16)
{
throw new IOException( "Unsupported Wave Format - EXPECTED: 1 " +
throw new IOException("Unsupported Wave Format - EXPECTED: 1 " +
"channel 16-bit samples FOUND: " +
mInputStream.getFormat().getChannels() + " channels " +
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples" );
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples");
}
/* Broadcast that we're at frame location 0 */
broadcast( 0 );
broadcast(0);
}
/**
* Reads the number of frames and sends a buffer to the listener
*/
@Override
public void next( int frames ) throws IOException
public void next(int frames) throws IOException
{
next( frames, true );
next(frames, true);
}
/**
* Reads the number of frames and optionally sends the buffer to the listener
*/
public void next( int frames, boolean broadcast ) throws IOException
public void next(int frames, boolean broadcast) throws IOException
{
if( mInputStream != null )
if(mInputStream != null)
{
byte[] buffer = new byte[ mBytesPerFrame * frames ];
byte[] buffer = new byte[mBytesPerFrame * frames];
/* Fill the buffer with samples from the file */
int samplesRead = mInputStream.read( buffer );
int samplesRead = mInputStream.read(buffer);
mFrameCounter += samplesRead;
broadcast( mFrameCounter );
broadcast(mFrameCounter);
if( broadcast && mListener != null )
if(broadcast && mListener != null)
{
if( samplesRead < buffer.length )
if(samplesRead < buffer.length)
{
if( samplesRead == -1 )
if(samplesRead == -1)
{
throw new IOException( "End of recording" );
throw new IOException("End of recording");
}
buffer = Arrays.copyOf( buffer, samplesRead );
buffer = Arrays.copyOf(buffer, samplesRead);
}
float[] samples = ConversionUtils
.convertFromSigned16BitSamples( buffer );
.convertFromSigned16BitSamples(buffer);
mListener.receive( new RealBuffer( samples ) );
mListener.receive(new RealBuffer(samples));
}
}
}
@@ -246,7 +259,7 @@ public class RealWaveSource extends RealSource
* the wave file
*/
@Override
public void setListener( Listener<RealBuffer> listener )
public void setListener(Listener<RealBuffer> listener)
{
mListener = listener;
}
@@ -254,7 +267,7 @@ public class RealWaveSource extends RealSource
/**
* Unregisters the listener from receiving sample buffers
*/
public void removeListener( Listener<RealBuffer> listener )
public void removeListener(Listener<RealBuffer> listener)
{
mListener = null;
}
@@ -271,24 +284,24 @@ public class RealWaveSource extends RealSource
return mFile;
}
private void broadcast( int byteLocation )
private void broadcast(int byteLocation)
{
int frameLocation = (int)( byteLocation / mBytesPerFrame );
int frameLocation = (int)(byteLocation / mBytesPerFrame);
if( mFrameLocationListener != null )
if(mFrameLocationListener != null)
{
mFrameLocationListener.frameLocationUpdated( frameLocation );
mFrameLocationListener.frameLocationUpdated(frameLocation);
}
}
@Override
public void setListener( IFrameLocationListener listener )
public void setListener(IFrameLocationListener listener)
{
mFrameLocationListener = listener;
}
@Override
public void removeListener( IFrameLocationListener listener )
public void removeListener(IFrameLocationListener listener)
{
mFrameLocationListener = null;
}