#90 [WIP] Adds ability to show streaming status on main application window using menu (View > Show Streaming Status). Resolves a number of issues with the SystemProperties class.

This commit is contained in:
Denny
2017-01-21 08:13:18 -05:00
parent 2d9c3c0aa4
commit 6b67a74055
10 changed files with 1820 additions and 1701 deletions

View File

@@ -118,12 +118,11 @@ public class AudioManager implements Listener<AudioPacket>, IAudioController
try try
{ {
setMixerChannelConfiguration(configuration); setMixerChannelConfiguration(configuration, false);
} }
catch(Exception e) catch(Exception e)
{ {
mLog.error("Couldn't set stored audio mixer/channel configuration" mLog.error("Couldn't set stored audio mixer/channel configuration - using default", e);
+ " - using default", e);
try try
{ {
@@ -131,8 +130,7 @@ public class AudioManager implements Listener<AudioPacket>, IAudioController
} }
catch(Exception e2) catch(Exception e2)
{ {
mLog.error("Couldn't set default audio mixer/channel " mLog.error("Couldn't set default audio mixer/channel configuration - no audio will be available", e2);
+ "configuration - no audio will be available", e2);
} }
} }
} }
@@ -217,8 +215,12 @@ public class AudioManager implements Listener<AudioPacket>, IAudioController
@Override @Override
public void setMixerChannelConfiguration(MixerChannelConfiguration entry) throws AudioException public void setMixerChannelConfiguration(MixerChannelConfiguration entry) throws AudioException
{ {
if(entry != null && setMixerChannelConfiguration(entry, true);
(entry.getMixerChannel() == MixerChannel.MONO || entry.getMixerChannel() == MixerChannel.STEREO)) }
public void setMixerChannelConfiguration(MixerChannelConfiguration entry, boolean saveSettings) throws AudioException
{
if(entry != null && (entry.getMixerChannel() == MixerChannel.MONO || entry.getMixerChannel() == MixerChannel.STEREO))
{ {
mControllerBroadcaster.broadcast(CONFIGURATION_CHANGE_STARTED); mControllerBroadcaster.broadcast(CONFIGURATION_CHANGE_STARTED);
@@ -260,11 +262,12 @@ public class AudioManager implements Listener<AudioPacket>, IAudioController
mControllerBroadcaster.broadcast(CONFIGURATION_CHANGE_COMPLETE); mControllerBroadcaster.broadcast(CONFIGURATION_CHANGE_COMPLETE);
if(saveSettings)
{
SystemProperties properties = SystemProperties.getInstance(); SystemProperties properties = SystemProperties.getInstance();
properties.set(AUDIO_MIXER_PROPERTY, entry.getMixer().getMixerInfo().getName()); properties.set(AUDIO_MIXER_PROPERTY, entry.getMixer().getMixerInfo().getName());
properties.set(AUDIO_CHANNELS_PROPERTY, entry.getMixerChannel().name()); properties.set(AUDIO_CHANNELS_PROPERTY, entry.getMixerChannel().name());
properties.save(); }
} }
} }

View File

@@ -585,7 +585,7 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
switch(column) switch(column)
{ {
case COLUMN_SERVER_ICON: case COLUMN_SERVER_ICON:
return null; return "Streaming";
case COLUMN_STREAM_NAME: case COLUMN_STREAM_NAME:
return "Name"; return "Name";
case COLUMN_BROADCASTER_STATUS: case COLUMN_BROADCASTER_STATUS:

View File

@@ -50,7 +50,7 @@ public class BroadcastPanel extends JPanel implements ActionListener, ListSelect
private AliasModel mAliasModel; private AliasModel mAliasModel;
private IconManager mIconManager; private IconManager mIconManager;
private JTable mBroadcastConfigurationTable; private BroadcastStatusPanel mBroadcastStatusPanel;
private JideSplitPane mSplitPane; private JideSplitPane mSplitPane;
private Editor<BroadcastConfiguration> mEmptyEditor = new EmptyEditor<>("Configuration:"); private Editor<BroadcastConfiguration> mEmptyEditor = new EmptyEditor<>("Configuration:");
private Editor<BroadcastConfiguration> mEditor; private Editor<BroadcastConfiguration> mEditor;
@@ -72,17 +72,11 @@ public class BroadcastPanel extends JPanel implements ActionListener, ListSelect
{ {
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]")); setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
mBroadcastConfigurationTable = new JTable(mBroadcastModel); mBroadcastStatusPanel = new BroadcastStatusPanel(mBroadcastModel);
mBroadcastConfigurationTable.setAutoCreateRowSorter(true);
mBroadcastConfigurationTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mBroadcastConfigurationTable.getSelectionModel().addListSelectionListener(BroadcastPanel.this);
mBroadcastConfigurationTable.getColumnModel().getColumn(BroadcastModel.COLUMN_SERVER_ICON).setPreferredWidth(1); mBroadcastStatusPanel.getTable().setAutoCreateRowSorter(true);
mBroadcastConfigurationTable.getColumnModel().getColumn(BroadcastModel.COLUMN_STREAM_NAME).setPreferredWidth(25); mBroadcastStatusPanel.getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mBroadcastConfigurationTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCASTER_STATUS) mBroadcastStatusPanel.getTable().getSelectionModel().addListSelectionListener(BroadcastPanel.this);
.setCellRenderer(new StatusCellRenderer());
JScrollPane scroller = new JScrollPane(mBroadcastConfigurationTable);
JPanel buttonsPanel = new JPanel(); JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill][grow,fill]", "[]")); buttonsPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill][grow,fill]", "[]"));
@@ -122,7 +116,7 @@ public class BroadcastPanel extends JPanel implements ActionListener, ListSelect
listAndButtonsPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill][]")); listAndButtonsPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill][]"));
listAndButtonsPanel.add(scroller, "wrap"); listAndButtonsPanel.add(mBroadcastStatusPanel, "wrap");
listAndButtonsPanel.add(buttonsPanel); listAndButtonsPanel.add(buttonsPanel);
mSplitPane = new JideSplitPane(JideSplitPane.HORIZONTAL_SPLIT); mSplitPane = new JideSplitPane(JideSplitPane.HORIZONTAL_SPLIT);
@@ -168,11 +162,11 @@ public class BroadcastPanel extends JPanel implements ActionListener, ListSelect
*/ */
private BroadcastConfiguration getSelectedBroadcastConfiguration() private BroadcastConfiguration getSelectedBroadcastConfiguration()
{ {
int viewRow = mBroadcastConfigurationTable.getSelectedRow(); int viewRow = mBroadcastStatusPanel.getTable().getSelectedRow();
if(viewRow >= 0) if(viewRow >= 0)
{ {
int modelRow = mBroadcastConfigurationTable.convertRowIndexToModel(viewRow); int modelRow = mBroadcastStatusPanel.getTable().convertRowIndexToModel(viewRow);
if(modelRow >= 0) if(modelRow >= 0)
{ {
@@ -255,75 +249,12 @@ public class BroadcastPanel extends JPanel implements ActionListener, ListSelect
mBroadcastModel.addBroadcastConfiguration(configuration); mBroadcastModel.addBroadcastConfiguration(configuration);
int modelRow = mBroadcastModel.getRowForConfiguration(configuration); int modelRow = mBroadcastModel.getRowForConfiguration(configuration);
int tableRow = mBroadcastConfigurationTable.convertRowIndexToView(modelRow); int tableRow = mBroadcastStatusPanel.getTable().convertRowIndexToView(modelRow);
mBroadcastConfigurationTable.changeSelection(tableRow, 0, false, false); mBroadcastStatusPanel.getTable().changeSelection(tableRow, 0, false, false);
} }
} }
}); });
} }
} }
/**
* Custom cell renderer for the broadcast state column.
*/
public class StatusCellRenderer extends DefaultTableCellRenderer
{
public StatusCellRenderer()
{
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
if(value instanceof BroadcastState)
{
BroadcastState state = (BroadcastState)value;
if(state == BroadcastState.CONNECTED)
{
setBackground(Color.GREEN);
setForeground(table.getForeground());
}
else if(state == BroadcastState.DISABLED)
{
setBackground(table.getBackground());
setForeground(Color.LIGHT_GRAY);
}
else if(state == BroadcastState.INVALID_SETTINGS)
{
setBackground(Color.YELLOW);
setForeground(table.getForeground());
}
else if(state.isErrorState())
{
setBackground(Color.RED);
setForeground(table.getForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
}
}
else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
return this;
}
}
} }

View File

@@ -0,0 +1,125 @@
/*******************************************************************************
* 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 audio.broadcast;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
public class BroadcastStatusPanel extends JPanel
{
private JTable mTable;
private JScrollPane mScrollPane;
private BroadcastModel mBroadcastModel;
public BroadcastStatusPanel(BroadcastModel broadcastModel)
{
mBroadcastModel = broadcastModel;
init();
}
public JTable getTable()
{
return mTable;
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
mTable = new JTable(mBroadcastModel);
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCASTER_STATUS).setCellRenderer(new StatusCellRenderer());
mScrollPane = new JScrollPane(mTable);
add(mScrollPane);
}
/**
* Custom cell renderer for the broadcast state column.
*/
public class StatusCellRenderer extends DefaultTableCellRenderer
{
public StatusCellRenderer()
{
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
if(value instanceof BroadcastState)
{
BroadcastState state = (BroadcastState)value;
if(state == BroadcastState.CONNECTED)
{
setBackground(Color.GREEN);
setForeground(table.getForeground());
}
else if(state == BroadcastState.DISABLED)
{
setBackground(table.getBackground());
setForeground(Color.LIGHT_GRAY);
}
else if(state == BroadcastState.INVALID_SETTINGS)
{
setBackground(Color.YELLOW);
setForeground(table.getForeground());
}
else if(state.isErrorState())
{
setBackground(Color.RED);
setForeground(table.getForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
}
}
else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
return this;
}
}
}

View File

@@ -24,6 +24,7 @@ import audio.AudioManager;
import audio.AudioPanel; import audio.AudioPanel;
import audio.broadcast.BroadcastModel; import audio.broadcast.BroadcastModel;
import audio.broadcast.BroadcastPanel; import audio.broadcast.BroadcastPanel;
import audio.broadcast.BroadcastStatusPanel;
import channel.metadata.ChannelMetadataViewer; import channel.metadata.ChannelMetadataViewer;
import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.swing.JideTabbedPane;
import controller.channel.ChannelController; import controller.channel.ChannelController;
@@ -34,6 +35,7 @@ import icon.IconManager;
import map.MapPanel; import map.MapPanel;
import map.MapService; import map.MapService;
import net.miginfocom.swing.MigLayout; import net.miginfocom.swing.MigLayout;
import properties.SystemProperties;
import settings.SettingsManager; import settings.SettingsManager;
import source.SourceManager; import source.SourceManager;
import source.tuner.TunerModel; import source.tuner.TunerModel;
@@ -54,6 +56,7 @@ public class ControllerPanel extends JPanel
private ChannelModel mChannelModel; private ChannelModel mChannelModel;
private MapPanel mMapPanel; private MapPanel mMapPanel;
private TunerViewPanel mTunerManagerPanel; private TunerViewPanel mTunerManagerPanel;
private BroadcastModel mBroadcastModel;
private JideTabbedPane mTabbedPane; private JideTabbedPane mTabbedPane;
protected JTable mChannelActivityTable = new JTable(); protected JTable mChannelActivityTable = new JTable();
@@ -70,6 +73,7 @@ public class ControllerPanel extends JPanel
SourceManager sourceManager, SourceManager sourceManager,
TunerModel tunerModel) TunerModel tunerModel)
{ {
mBroadcastModel = broadcastModel;
mChannelModel = channelModel; mChannelModel = channelModel;
mAudioPanel = new AudioPanel(iconManager, settingsManager, sourceManager, audioManager); mAudioPanel = new AudioPanel(iconManager, settingsManager, sourceManager, audioManager);
@@ -91,7 +95,7 @@ public class ControllerPanel extends JPanel
private void init() private void init()
{ {
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[]0[grow,fill]")); setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[]0[grow,fill]0[]"));
add(mAudioPanel, "wrap"); add(mAudioPanel, "wrap");
@@ -109,6 +113,6 @@ public class ControllerPanel extends JPanel
//Set preferred size to influence the split between these panels //Set preferred size to influence the split between these panels
mTabbedPane.setPreferredSize(new Dimension(880, 500)); mTabbedPane.setPreferredSize(new Dimension(880, 500));
add(mTabbedPane); add(mTabbedPane,"wrap");
} }
} }

View File

@@ -1,6 +1,6 @@
/******************************************************************************* /*******************************************************************************
* SDR Trunk * sdrtrunk
* Copyright (C) 2014-2016 Dennis Sheirer * Copyright (C) 2014-2017 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -14,20 +14,20 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/ ******************************************************************************/
package controller.channel; package controller.channel;
import controller.channel.Channel.ChannelType;
import controller.channel.ChannelEvent.Event;
import module.decode.DecoderType;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.table.AbstractTableModel;
import module.decode.DecoderType;
import controller.channel.Channel.ChannelType;
import controller.channel.ChannelEvent.Event;
/** /**
* Channel Model * Channel Model
*/ */
@@ -35,6 +35,17 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final int COLUMN_ENABLED = 0;
public static final int COLUMN_SYSTEM = 1;
public static final int COLUMN_SITE = 2;
public static final int COLUMN_NAME = 3;
public static final int COLUMN_ALIAS_LIST = 4;
public static final int COLUMN_SOURCE = 5;
public static final int COLUMN_DECODER = 6;
private static final String[] COLUMN_NAMES = new String[] {"Enabled", "System", "Site", "Name", "Alias List",
"Source", "Decoder"};
private List<Channel> mChannels = new CopyOnWriteArrayList<>(); private List<Channel> mChannels = new CopyOnWriteArrayList<>();
private List<Channel> mTrafficChannels = new CopyOnWriteArrayList<>(); private List<Channel> mTrafficChannels = new CopyOnWriteArrayList<>();
private List<ChannelEventListener> mListeners = new CopyOnWriteArrayList<>(); private List<ChannelEventListener> mListeners = new CopyOnWriteArrayList<>();
@@ -48,14 +59,14 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
*/ */
public List<Channel> getChannels() public List<Channel> getChannels()
{ {
return Collections.unmodifiableList( mChannels ); return Collections.unmodifiableList(mChannels);
} }
public Channel getChannelAtIndex( int row ) public Channel getChannelAtIndex(int row)
{ {
if( mChannels.size() >= row ) if(row < mChannels.size())
{ {
return mChannels.get( row ); return mChannels.get(row);
} }
return null; return null;
@@ -68,15 +79,15 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
{ {
List<String> systems = new ArrayList<>(); List<String> systems = new ArrayList<>();
for( Channel channel: mChannels ) for(Channel channel : mChannels)
{ {
if( channel.hasSystem() && !systems.contains( channel.getSystem() ) ) if(channel.hasSystem() && !systems.contains(channel.getSystem()))
{ {
systems.add( channel.getSystem() ); systems.add(channel.getSystem());
} }
} }
Collections.sort( systems ); Collections.sort(systems);
return systems; return systems;
} }
@@ -85,25 +96,25 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
* Returns a list of unique site values for all channels that have a matching * Returns a list of unique site values for all channels that have a matching
* system value * system value
*/ */
public List<String> getSites( String system ) public List<String> getSites(String system)
{ {
List<String> sites = new ArrayList<>(); List<String> sites = new ArrayList<>();
if( system != null ) if(system != null)
{ {
for( Channel channel: mChannels ) for(Channel channel : mChannels)
{ {
if( channel.hasSystem() && if(channel.hasSystem() &&
system.equals( channel.getSystem() ) && system.equals(channel.getSystem()) &&
channel.hasSite() && channel.hasSite() &&
!sites.contains( channel.getSite() ) ) !sites.contains(channel.getSite()))
{ {
sites.add( channel.getSite() ); sites.add(channel.getSite());
} }
} }
} }
Collections.sort( sites ); Collections.sort(sites);
return sites; return sites;
} }
@@ -112,32 +123,32 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
* Broadcasts the channel event to all registered listeners * Broadcasts the channel event to all registered listeners
*/ */
@Override @Override
public void broadcast( ChannelEvent event ) public void broadcast(ChannelEvent event)
{ {
for( ChannelEventListener listener: mListeners ) for(ChannelEventListener listener : mListeners)
{ {
listener.channelChanged( event ); listener.channelChanged(event);
} }
if( event.getChannel().getChannelType() == ChannelType.STANDARD ) if(event.getChannel().getChannelType() == ChannelType.STANDARD)
{ {
switch( event.getEvent() ) switch(event.getEvent())
{ {
case NOTIFICATION_CONFIGURATION_CHANGE: case NOTIFICATION_CONFIGURATION_CHANGE:
case NOTIFICATION_PROCESSING_START: case NOTIFICATION_PROCESSING_START:
case NOTIFICATION_PROCESSING_STOP: case NOTIFICATION_PROCESSING_STOP:
case NOTIFICATION_SELECTION_CHANGE: case NOTIFICATION_SELECTION_CHANGE:
int index = mChannels.indexOf( event.getChannel() ); int index = mChannels.indexOf(event.getChannel());
fireTableRowsUpdated( index, index ); fireTableRowsUpdated(index, index);
break; break;
default: default:
break; break;
} }
} }
if( event.getEvent() == Event.REQUEST_DELETE ) if(event.getEvent() == Event.REQUEST_DELETE)
{ {
removeChannel( event.getChannel() ); removeChannel(event.getChannel());
} }
} }
@@ -145,43 +156,43 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
* Bulk loading of channel list. Each channel is added and a channel add * Bulk loading of channel list. Each channel is added and a channel add
* event is broadcast. * event is broadcast.
*/ */
public void addChannels( List<Channel> channels ) public void addChannels(List<Channel> channels)
{ {
for( Channel channel: channels ) for(Channel channel : channels)
{ {
addChannel( channel ); addChannel(channel);
} }
} }
/** /**
* Adds the channel to the model and broadcasts a channel add event * Adds the channel to the model and broadcasts a channel add event
*/ */
public int addChannel( Channel channel ) public int addChannel(Channel channel)
{ {
int index = -1; int index = -1;
switch( channel.getChannelType() ) switch(channel.getChannelType())
{ {
case STANDARD: case STANDARD:
mChannels.add( channel ); mChannels.add(channel);
index = mChannels.size() - 1; index = mChannels.size() - 1;
fireTableRowsInserted( index, index ); fireTableRowsInserted(index, index);
break; break;
case TRAFFIC: case TRAFFIC:
mTrafficChannels.add( channel ); mTrafficChannels.add(channel);
index = mChannels.size() - 1; index = mChannels.size() - 1;
break; break;
default: default:
break; break;
} }
broadcast( new ChannelEvent( channel, Event.NOTIFICATION_ADD ) ); broadcast(new ChannelEvent(channel, Event.NOTIFICATION_ADD));
if( channel.getEnabled() ) if(channel.getEnabled())
{ {
broadcast( new ChannelEvent( channel, Event.REQUEST_ENABLE ) ); broadcast(new ChannelEvent(channel, Event.REQUEST_ENABLE));
} }
return index; return index;
@@ -190,30 +201,30 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
/** /**
* Removes the channel from the model and broadcasts a channel remove event * Removes the channel from the model and broadcasts a channel remove event
*/ */
public void removeChannel( Channel channel ) public void removeChannel(Channel channel)
{ {
if( channel != null ) if(channel != null)
{ {
switch( channel.getChannelType() ) switch(channel.getChannelType())
{ {
case STANDARD: case STANDARD:
int index = mChannels.indexOf( channel ); int index = mChannels.indexOf(channel);
mChannels.remove( channel ); mChannels.remove(channel);
if( index >= 0 ) if(index >= 0)
{ {
fireTableRowsDeleted( index, index ); fireTableRowsDeleted(index, index);
} }
break; break;
case TRAFFIC: case TRAFFIC:
mTrafficChannels.remove( channel ); mTrafficChannels.remove(channel);
break; break;
default: default:
break; break;
} }
broadcast( new ChannelEvent( channel, Event.NOTIFICATION_DELETE ) ); broadcast(new ChannelEvent(channel, Event.NOTIFICATION_DELETE));
} }
} }
@@ -222,40 +233,39 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
* *
* @param start frequency of the range * @param start frequency of the range
* @param stop frequency of the range * @param stop frequency of the range
*
* @return list of channels or an empty list if none fall within the range * @return list of channels or an empty list if none fall within the range
*/ */
public List<Channel> getChannelsInFrequencyRange( long start, long stop ) public List<Channel> getChannelsInFrequencyRange(long start, long stop)
{ {
List<Channel> channels = new ArrayList<>(); List<Channel> channels = new ArrayList<>();
for( Channel channel: mChannels ) for(Channel channel : mChannels)
{ {
if( channel.isWithin( start, stop ) ) if(channel.isWithin(start, stop))
{ {
channels.add( channel ); channels.add(channel);
} }
} }
for( Channel channel: mTrafficChannels ) for(Channel channel : mTrafficChannels)
{ {
if( channel.isWithin( start, stop ) ) if(channel.isWithin(start, stop))
{ {
channels.add( channel ); channels.add(channel);
} }
} }
return channels; return channels;
} }
public void addListener( ChannelEventListener listener ) public void addListener(ChannelEventListener listener)
{ {
mListeners.add( listener ); mListeners.add(listener);
} }
public void removeListener( ChannelEventListener listener ) public void removeListener(ChannelEventListener listener)
{ {
mListeners.remove( listener ); mListeners.remove(listener);
} }
//Table Model Interface Methods - standard channels only //Table Model Interface Methods - standard channels only
@@ -268,76 +278,66 @@ public class ChannelModel extends AbstractTableModel implements IChannelEventBro
@Override @Override
public int getColumnCount() public int getColumnCount()
{ {
return 6; return COLUMN_NAMES.length;
} }
@Override @Override
public String getColumnName( int columnIndex ) public String getColumnName(int columnIndex)
{ {
switch( columnIndex ) if(columnIndex < COLUMN_NAMES.length)
{ {
case 0: return COLUMN_NAMES[columnIndex];
return "System";
case 1:
return "Site";
case 2:
return "Name";
case 3:
return "Alias List";
case 4:
return "Source";
case 5:
return "Decoder";
} }
return null; return null;
} }
@Override @Override
public Class<?> getColumnClass( int columnIndex ) public Class<?> getColumnClass(int columnIndex)
{ {
return String.class; return String.class;
} }
@Override @Override
public boolean isCellEditable( int rowIndex, int columnIndex ) public boolean isCellEditable(int rowIndex, int columnIndex)
{ {
return false; return false;
} }
@Override @Override
public Object getValueAt( int rowIndex, int columnIndex ) public Object getValueAt(int rowIndex, int columnIndex)
{ {
Channel channel = mChannels.get( rowIndex ); Channel channel = mChannels.get(rowIndex);
switch( columnIndex ) switch(columnIndex)
{ {
case 0: case COLUMN_ENABLED:
return channel.getEnabled() ? "Enabled" : null;
case COLUMN_SYSTEM:
return channel.getSystem(); return channel.getSystem();
case 1: case COLUMN_SITE:
return channel.getSite(); return channel.getSite();
case 2: case COLUMN_NAME:
return channel.getName(); return channel.getName();
case 3: case COLUMN_ALIAS_LIST:
return channel.getAliasListName(); return channel.getAliasListName();
case 4: case COLUMN_SOURCE:
return channel.getSourceConfiguration().getDescription(); return channel.getSourceConfiguration().getDescription();
case 5: case COLUMN_DECODER:
return channel.getDecodeConfiguration() return channel.getDecodeConfiguration().getDecoderType().getShortDisplayString();
.getDecoderType().getShortDisplayString();
} }
return null; return null;
} }
@Override @Override
public void setValueAt( Object aValue, int rowIndex, int columnIndex ) public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{ {
throw new IllegalArgumentException( "Not yet implemented" ); throw new IllegalArgumentException("Not yet implemented");
} }
public void createChannel( DecoderType decoderType, long frequency ) public void createChannel(DecoderType decoderType, long frequency)
{ {
throw new UnsupportedOperationException( "Not yet implemented" ); throw new UnsupportedOperationException("Not yet implemented");
} }
} }

View File

@@ -21,6 +21,7 @@ import alias.AliasModel;
import alias.action.AliasActionManager; import alias.action.AliasActionManager;
import audio.AudioManager; import audio.AudioManager;
import audio.broadcast.BroadcastModel; import audio.broadcast.BroadcastModel;
import audio.broadcast.BroadcastStatusPanel;
import com.jidesoft.swing.JideSplitPane; import com.jidesoft.swing.JideSplitPane;
import controller.ControllerPanel; import controller.ControllerPanel;
import controller.ThreadPoolManager; import controller.ThreadPoolManager;
@@ -65,12 +66,17 @@ import java.util.concurrent.TimeUnit;
public class SDRTrunk implements Listener<TunerEvent> public class SDRTrunk implements Listener<TunerEvent>
{ {
private final static Logger mLog = LoggerFactory.getLogger(SDRTrunk.class); private final static Logger mLog = LoggerFactory.getLogger(SDRTrunk.class);
private static final String PROPERTY_BROADCAST_STATUS_VISIBLE = "main.broadcast.status.visible";
private boolean mBroadcastStatusVisible;
private IconManager mIconManager; private IconManager mIconManager;
private BroadcastStatusPanel mBroadcastStatusPanel;
private BroadcastModel mBroadcastModel;
private ControllerPanel mControllerPanel; private ControllerPanel mControllerPanel;
private SettingsManager mSettingsManager; private SettingsManager mSettingsManager;
private SpectralDisplayPanel mSpectralPanel; private SpectralDisplayPanel mSpectralPanel;
private JFrame mMainGui = new JFrame(); private JFrame mMainGui = new JFrame();
private JideSplitPane mSplitPane;
private String mTitle; private String mTitle;
@@ -139,14 +145,14 @@ public class SDRTrunk implements Listener<TunerEvent>
AudioManager audioManager = new AudioManager(threadPoolManager, sourceManager.getMixerManager()); AudioManager audioManager = new AudioManager(threadPoolManager, sourceManager.getMixerManager());
channelProcessingManager.addAudioPacketListener(audioManager); channelProcessingManager.addAudioPacketListener(audioManager);
BroadcastModel broadcastModel = new BroadcastModel(threadPoolManager, mIconManager); mBroadcastModel = new BroadcastModel(threadPoolManager, mIconManager);
channelProcessingManager.addAudioPacketListener(broadcastModel); channelProcessingManager.addAudioPacketListener(mBroadcastModel);
MapService mapService = new MapService(mIconManager); MapService mapService = new MapService(mIconManager);
channelProcessingManager.addMessageListener(mapService); channelProcessingManager.addMessageListener(mapService);
mControllerPanel = new ControllerPanel(audioManager, aliasModel, broadcastModel, mControllerPanel = new ControllerPanel(audioManager, aliasModel, mBroadcastModel,
channelModel, channelMapModel, channelProcessingManager, mIconManager, channelModel, channelMapModel, channelProcessingManager, mIconManager,
mapService, mSettingsManager, sourceManager, tunerModel); mapService, mSettingsManager, sourceManager, tunerModel);
@@ -160,7 +166,7 @@ public class SDRTrunk implements Listener<TunerEvent>
tunerModel.addListener(this); tunerModel.addListener(this);
PlaylistManager playlistManager = new PlaylistManager(threadPoolManager, PlaylistManager playlistManager = new PlaylistManager(threadPoolManager,
aliasModel, broadcastModel, channelModel, channelMapModel); aliasModel, mBroadcastModel, channelModel, channelMapModel);
playlistManager.init(); playlistManager.init();
@@ -209,9 +215,7 @@ public class SDRTrunk implements Listener<TunerEvent>
*/ */
private void initGUI() private void initGUI()
{ {
mMainGui.setLayout(new MigLayout("insets 0 0 0 0 ", mMainGui.setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
"[grow,fill]",
"[grow,fill]"));
/** /**
* Setup main JFrame window * Setup main JFrame window
@@ -225,12 +229,20 @@ public class SDRTrunk implements Listener<TunerEvent>
mSpectralPanel.setPreferredSize(new Dimension(1280, 300)); mSpectralPanel.setPreferredSize(new Dimension(1280, 300));
mControllerPanel.setPreferredSize(new Dimension(1280, 500)); mControllerPanel.setPreferredSize(new Dimension(1280, 500));
JideSplitPane splitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT); mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
splitPane.setDividerSize(5); mSplitPane.setDividerSize(5);
splitPane.add(mSpectralPanel); mSplitPane.add(mSpectralPanel);
splitPane.add(mControllerPanel); mSplitPane.add(mControllerPanel);
mMainGui.add(splitPane, "cell 0 0,span,grow"); mBroadcastStatusVisible = SystemProperties.getInstance().get(PROPERTY_BROADCAST_STATUS_VISIBLE, false);
//Show broadcast status panel when user requests - disabled by default
if(mBroadcastStatusVisible)
{
mSplitPane.add(getBroadcastStatusPanel());
}
mMainGui.add(mSplitPane, "cell 0 0,span,grow");
/** /**
* Menu items * Menu items
@@ -291,6 +303,12 @@ public class SDRTrunk implements Listener<TunerEvent>
fileMenu.add(exitMenu); fileMenu.add(exitMenu);
JMenu viewMenu = new JMenu("View");
viewMenu.add(new BroadcastStatusVisibleMenuItem(mControllerPanel));
menuBar.add(viewMenu);
JMenuItem screenCaptureItem = new JMenuItem("Screen Capture"); JMenuItem screenCaptureItem = new JMenuItem("Screen Capture");
screenCaptureItem.setMnemonic(KeyEvent.VK_C); screenCaptureItem.setMnemonic(KeyEvent.VK_C);
@@ -360,6 +378,50 @@ public class SDRTrunk implements Listener<TunerEvent>
menuBar.add(screenCaptureItem); menuBar.add(screenCaptureItem);
} }
/**
* Lazy constructor for broadcast status panel
*/
private BroadcastStatusPanel getBroadcastStatusPanel()
{
if(mBroadcastStatusPanel == null)
{
mBroadcastStatusPanel = new BroadcastStatusPanel(mBroadcastModel);
mBroadcastStatusPanel.setPreferredSize(new Dimension(880, 100));
mBroadcastStatusPanel.getTable().setEnabled(false);
}
return mBroadcastStatusPanel;
}
/**
* Toggles visibility of the broadcast channels status panel at the bottom of the controller panel
*/
private void toggleBroadcastStatusPanelVisibility()
{
mBroadcastStatusVisible = !mBroadcastStatusVisible;
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
if(mBroadcastStatusVisible)
{
mSplitPane.add(getBroadcastStatusPanel());
}
else
{
mSplitPane.remove(getBroadcastStatusPanel());
}
mMainGui.revalidate();
}
});
SystemProperties.getInstance().set(PROPERTY_BROADCAST_STATUS_VISIBLE, mBroadcastStatusVisible);
}
/** /**
* Loads the application properties file from the user's home directory, * Loads the application properties file from the user's home directory,
* creating the properties file for the first-time, if necessary * creating the properties file for the first-time, if necessary
@@ -435,4 +497,28 @@ public class SDRTrunk implements Listener<TunerEvent>
mMainGui.setTitle(mTitle + " - " + event.getTuner().getName()); mMainGui.setTitle(mTitle + " - " + event.getTuner().getName());
} }
} }
public class BroadcastStatusVisibleMenuItem extends JCheckBoxMenuItem
{
private ControllerPanel mControllerPanel;
public BroadcastStatusVisibleMenuItem(ControllerPanel controllerPanel)
{
super("Show Streaming Status");
mControllerPanel = controllerPanel;
setSelected(mBroadcastStatusPanel != null);
addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
toggleBroadcastStatusPanelVisibility();
setSelected(mBroadcastStatusVisible);
}
});
}
}
} }

View File

@@ -1,6 +1,6 @@
/******************************************************************************* /*******************************************************************************
* SDR Trunk * sdrtrunk
* Copyright (C) 2014 Dennis Sheirer * Copyright (C) 2014-2017 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -14,6 +14,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/ ******************************************************************************/
package properties; package properties;
@@ -33,24 +34,27 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* SystemProperties - provides an isolated instance of properties for the * SystemProperties - provides an isolated instance of properties for the application
* application
*/ */
public class SystemProperties public class SystemProperties
{ {
private final static Logger mLog = private final static Logger mLog = LoggerFactory.getLogger(SystemProperties.class);
LoggerFactory.getLogger(SystemProperties.class);
private static String sDEFAULT_APP_ROOT = "SDRTrunk"; private static String DEFAULT_APP_ROOT = "SDRTrunk";
private static String sPROPERTIES_FILENAME = "SDRTrunk.properties"; private static String PROPERTIES_FILENAME = "SDRTrunk.properties";
private static SystemProperties mInstance; private static SystemProperties INSTANCE;
private static Properties mProperties; private static Properties mProperties;
private Path mPropertiesPath; private Path mPropertiesPath;
private String mApplicationName; private String mApplicationName;
private AtomicBoolean mSavePending = new AtomicBoolean();
private ScheduledExecutorService mScheduledExecutorService;
private SystemProperties() private SystemProperties()
{ {
@@ -64,50 +68,27 @@ public class SystemProperties
*/ */
public static SystemProperties getInstance() public static SystemProperties getInstance()
{ {
if(mInstance == null) if(INSTANCE == null)
{ {
mInstance = new SystemProperties(); INSTANCE = new SystemProperties();
} }
return mInstance; return INSTANCE;
} }
/** /**
* Saves any currently changed settings to the application properties file * Saves any currently changed settings to the application properties file
*/ */
public void save() private void save()
{ {
Path propsPath = if(mSavePending.compareAndSet(false, true))
getApplicationRootPath().resolve(sPROPERTIES_FILENAME); {
if(mScheduledExecutorService == null)
{
mScheduledExecutorService = Executors.newScheduledThreadPool(1);
}
OutputStream out = null; mScheduledExecutorService.schedule(new SavePropertiesTask(), 2, TimeUnit.SECONDS);
try
{
out = new FileOutputStream(propsPath.toString());
String comments =
"SDRTrunk - SDR Trunking Decoder Application Settings";
mProperties.store(out, comments);
}
catch(Exception e)
{
mLog.error("SystemProperties - exception while saving " +
"application properties", e);
}
finally
{
if(out != null)
{
try
{
out.close();
}
catch(IOException e)
{
}
}
} }
} }
@@ -120,12 +101,12 @@ public class SystemProperties
{ {
Path retVal = null; Path retVal = null;
String root = get("root.directory", sDEFAULT_APP_ROOT); String root = get("root.directory", DEFAULT_APP_ROOT);
if(root.equalsIgnoreCase(sDEFAULT_APP_ROOT)) if(root.equalsIgnoreCase(DEFAULT_APP_ROOT))
{ {
retVal = Paths.get( retVal = Paths.get(
System.getProperty("user.home"), sDEFAULT_APP_ROOT); System.getProperty("user.home"), DEFAULT_APP_ROOT);
} }
else else
{ {
@@ -147,8 +128,7 @@ public class SystemProperties
} }
catch(IOException e) catch(IOException e)
{ {
mLog.error("SystemProperties - exception while creating " + mLog.error("SystemProperties - exception while creating app folder [" + folder + "]", e);
"app folder [" + folder + "]", e);
} }
} }
@@ -169,8 +149,6 @@ public class SystemProperties
/** /**
* Loads the properties file into this properties set * Loads the properties file into this properties set
*
* @param file
*/ */
public void load(Path propertiesPath) public void load(Path propertiesPath)
{ {
@@ -178,44 +156,20 @@ public class SystemProperties
{ {
mPropertiesPath = propertiesPath; mPropertiesPath = propertiesPath;
InputStream in = null; if(Files.exists(mPropertiesPath))
try
{ {
in = new FileInputStream(propertiesPath.toString()); try(InputStream in = new FileInputStream(propertiesPath.toString()))
}
catch(FileNotFoundException e)
{
mLog.error("SDRTrunk - exception while opening inputstream on " +
"application properties file", e);
}
if(in != null)
{
try
{ {
mProperties.load(in); mProperties.load(in);
} }
catch(IOException e) catch(IOException ioe)
{ {
mLog.error("SDRTrunk - exception while loading properties " + mLog.error("Error loading system properties file", ioe.getMessage());
"inputstream into SystemProperties", e);
}
finally
{
try
{
in.close();
}
catch(IOException e)
{
}
} }
} }
} }
mLog.info("SystemProperties - loaded [" + mLog.info("SystemProperties - loaded [" + propertiesPath.toString() + "]");
propertiesPath.toString() + "]");
} }
public String getApplicationName() public String getApplicationName()
@@ -339,6 +293,22 @@ public class SystemProperties
save(); save();
} }
/**
* Sets (overrides) the property key with the new boolean value
*/
public void set(String key, boolean value)
{
set(key, String.valueOf(value));
}
/**
* Sets (overrides) the property key with the new integer value
*/
public void set(String key, int value)
{
set(key, String.valueOf(value));
}
/** /**
* Gets the named color property, storing the default value in properties file if it doesn't exist. * Gets the named color property, storing the default value in properties file if it doesn't exist.
* *
@@ -362,4 +332,25 @@ public class SystemProperties
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
} }
public class SavePropertiesTask implements Runnable
{
@Override
public void run()
{
if(mSavePending.compareAndSet(true, false))
{
Path propsPath = getApplicationRootPath().resolve(PROPERTIES_FILENAME);
try(OutputStream out = new FileOutputStream(propsPath.toString()))
{
String comments = "SDRTrunk - SDR Trunking Decoder Application Settings";
mProperties.store(out, comments);
}
catch(IOException ioe)
{
mLog.error("Error saving system properties file [" + propsPath.toString() + "]", ioe);
}
}
}
}
} }

View File

@@ -1,6 +1,6 @@
/******************************************************************************* /*******************************************************************************
* SDR Trunk * sdrtrunk
* Copyright (C) 2014,2015 Dennis Sheirer * Copyright (C) 2014-2017 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -14,9 +14,25 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/ ******************************************************************************/
package spectrum; package spectrum;
import controller.NamingThreadFactory;
import dsp.filter.Window;
import dsp.filter.Window.WindowType;
import org.jtransforms.fft.FloatFFT_1D;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import sample.Buffer;
import sample.Listener;
import sample.SampleType;
import sample.complex.ComplexBuffer;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.IFrequencyChangeProcessor;
import spectrum.converter.DFTResultsConverter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
@@ -27,45 +43,25 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.jtransforms.fft.FloatFFT_1D;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import sample.Buffer;
import sample.Listener;
import sample.SampleType;
import sample.complex.ComplexBuffer;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.IFrequencyChangeProcessor;
import spectrum.converter.DFTResultsConverter;
import controller.NamingThreadFactory;
import dsp.filter.Window;
import dsp.filter.Window.WindowType;
/** /**
* Processes both complex samples or float samples and dispatches a float array * Processes both complex samples or float samples and dispatches a float array
* of DFT results, using configurable fft size and output dispatch timelines. * of DFT results, using configurable fft size and output dispatch timelines.
*/ */
public class DFTProcessor implements Listener<ComplexBuffer>, public class DFTProcessor implements Listener<ComplexBuffer>, IFrequencyChangeProcessor, IDFTWidthChangeProcessor
IFrequencyChangeProcessor,
IDFTWidthChangeProcessor
{ {
private final static Logger mLog = private final static Logger mLog = LoggerFactory.getLogger(DFTProcessor.class);
LoggerFactory.getLogger( DFTProcessor.class );
private CopyOnWriteArrayList<DFTResultsConverter> mListeners = private CopyOnWriteArrayList<DFTResultsConverter> mListeners = new CopyOnWriteArrayList<DFTResultsConverter>();
new CopyOnWriteArrayList<DFTResultsConverter>();
//Fixed size sample queue. We set the size at 12 based on the highest //Fixed size sample queue. We set the size at 12 based on the highest
//sample rate tuner (10 MHz) producing 153 frames per second and the lowest //sample rate tuner (10 MHz) producing 153 frames per second and the lowest
//DFT processing frame rate of 12 frames per second. This means that the //DFT processing frame rate of 12 frames per second. This means that the
//maximum size needed is 153 / 12 = 11 frames per DFT processing iteration //maximum size needed is 153 / 12 = 11 frames per DFT processing iteration
//so we set it at 12. //so we set it at 12.
private BlockingQueue<ComplexBuffer> mQueue = new ArrayBlockingQueue<>( 12 ); private BlockingQueue<ComplexBuffer> mQueue = new ArrayBlockingQueue<>(12);
private ScheduledExecutorService mScheduler = Executors private ScheduledExecutorService mScheduler = Executors
.newScheduledThreadPool( 1, new NamingThreadFactory( "spectrum dft" ) ); .newScheduledThreadPool(1, new NamingThreadFactory("spectrum dft processor"));
public static final String FRAME_RATE_PROPERTY = "spectral.display.frame.rate"; public static final String FRAME_RATE_PROPERTY = "spectral.display.frame.rate";
@@ -78,14 +74,14 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
* with minimal bin leakage/smearing */ * with minimal bin leakage/smearing */
private WindowType mWindowType = Window.WindowType.HANNING; private WindowType mWindowType = Window.WindowType.HANNING;
private FloatFFT_1D mFFT = new FloatFFT_1D( mDFTSize.getSize() ); private FloatFFT_1D mFFT = new FloatFFT_1D(mDFTSize.getSize());
private int mFrameRate; private int mFrameRate;
private int mSampleRate; private int mSampleRate;
private int mFFTFloatsPerFrame; private int mFFTFloatsPerFrame;
private float mNewFloatsPerFrame; private float mNewFloatsPerFrame;
private float mNewFloatResidual; private float mNewFloatResidual;
private float[] mPreviousFrame = new float[ 8192 ]; private float[] mPreviousFrame = new float[8192];
private float[] mCurrentBuffer; private float[] mCurrentBuffer;
private int mCurrentBufferPointer = 0; private int mCurrentBufferPointer = 0;
@@ -94,19 +90,12 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
private AtomicBoolean mRunning = new AtomicBoolean(); private AtomicBoolean mRunning = new AtomicBoolean();
public DFTProcessor( SampleType sampleType ) public DFTProcessor(SampleType sampleType)
{ {
setSampleType( sampleType ); setSampleType(sampleType);
setFrameRate( 20 ); mFrameRate = SystemProperties.getInstance().get(FRAME_RATE_PROPERTY, 20);
calculateConsumptionRate();
loadSettings(); start();
}
private void loadSettings()
{
int frameRate = SystemProperties.getInstance().get( FRAME_RATE_PROPERTY, 20 );
setFrameRate( frameRate );
} }
public void dispose() public void dispose()
@@ -124,19 +113,17 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
return mWindowType; return mWindowType;
} }
public void setWindowType( WindowType windowType ) public void setWindowType(WindowType windowType)
{ {
mWindowType = windowType; mWindowType = windowType;
if( mSampleType == SampleType.COMPLEX ) if(mSampleType == SampleType.COMPLEX)
{ {
mWindow = Window.getWindow( mWindowType, mWindow = Window.getWindow(mWindowType, mDFTSize.getSize() * 2);
mDFTSize.getSize() * 2 );
} }
else else
{ {
mWindow = Window.getWindow( mWindowType, mWindow = Window.getWindow(mWindowType, mDFTSize.getSize());
mDFTSize.getSize() );
} }
} }
@@ -144,10 +131,10 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
* Sets the processor mode to Float or Complex, depending on the sample * Sets the processor mode to Float or Complex, depending on the sample
* types that will be delivered for processing * types that will be delivered for processing
*/ */
public void setSampleType( SampleType type ) public void setSampleType(SampleType type)
{ {
mSampleType = type; mSampleType = type;
setWindowType( mWindowType ); setWindowType(mWindowType);
} }
public SampleType getSampleType() public SampleType getSampleType()
@@ -159,7 +146,7 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
* Queues an FFT size change request. The scheduled executor will apply * Queues an FFT size change request. The scheduled executor will apply
* the change when it runs. * the change when it runs.
*/ */
public void setDFTSize( DFTSize size ) public void setDFTSize(DFTSize size)
{ {
mNewDFTSize = size; mNewDFTSize = size;
} }
@@ -174,23 +161,21 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
return mFrameRate; return mFrameRate;
} }
public void setFrameRate( int framesPerSecond ) public void setFrameRate(int framesPerSecond)
{ {
//TODO: make sure frame rate & sample rate sample requirement doesn't //TODO: make sure frame rate & sample rate sample requirement doesn't
//expect overlap greater than the previous frame length //expect overlap greater than the previous frame length
if( framesPerSecond < 1 || framesPerSecond > 1000 ) if(framesPerSecond < 1 || framesPerSecond > 1000)
{ {
throw new IllegalArgumentException( "DFTProcessor cannot run " throw new IllegalArgumentException("DFTProcessor cannot run "
+ "more than 1000 times per second -- requested setting:" + "more than 1000 times per second -- requested setting:"
+ framesPerSecond ); + framesPerSecond);
} }
mFrameRate = framesPerSecond; mFrameRate = framesPerSecond;
SystemProperties properties = SystemProperties.getInstance(); SystemProperties.getInstance().set(FRAME_RATE_PROPERTY, mFrameRate);
properties.set( FRAME_RATE_PROPERTY, String.valueOf( mFrameRate ) );
calculateConsumptionRate(); calculateConsumptionRate();
@@ -202,17 +187,17 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
/** /**
* Reset the scheduler * Reset the scheduler
*/ */
mScheduler = Executors.newScheduledThreadPool( 1, new NamingThreadFactory( "spectrum dft" ) ); mScheduler = Executors.newScheduledThreadPool(1, new NamingThreadFactory("spectrum dft"));
/** /**
* Schedule the DFT to run calculations at a fixed rate * Schedule the DFT to run calculations at a fixed rate
*/ */
int initialDelay = 0; int initialDelay = 0;
int period = (int)( 1000 / mFrameRate ); int period = (int) (1000 / mFrameRate);
TimeUnit unit = TimeUnit.MILLISECONDS; TimeUnit unit = TimeUnit.MILLISECONDS;
mScheduler.scheduleAtFixedRate( new DFTCalculationTask(), mScheduler.scheduleAtFixedRate(new DFTCalculationTask(),
initialDelay, period, unit ); initialDelay, period, unit);
} }
public void stop() public void stop()
@@ -224,9 +209,9 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
{ {
mScheduler.shutdown(); mScheduler.shutdown();
mScheduler.awaitTermination( 100, TimeUnit.MILLISECONDS ); mScheduler.awaitTermination(100, TimeUnit.MILLISECONDS);
} }
catch ( InterruptedException e ) catch(InterruptedException e)
{ {
/* Do nothing ... we're shutting down */ /* Do nothing ... we're shutting down */
// mLog.error( "DFTProcessor - exception while awaiting shutdown of " // mLog.error( "DFTProcessor - exception while awaiting shutdown of "
@@ -249,9 +234,9 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
* Places the sample into a transfer queue for future processing. * Places the sample into a transfer queue for future processing.
*/ */
@Override @Override
public void receive( ComplexBuffer sampleBuffer ) public void receive(ComplexBuffer sampleBuffer)
{ {
mQueue.offer( sampleBuffer ); mQueue.offer(sampleBuffer);
} }
private void getNextBuffer() private void getNextBuffer()
@@ -263,7 +248,7 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
Buffer buffer = mQueue.take(); Buffer buffer = mQueue.take();
mCurrentBuffer = buffer.getSamples(); mCurrentBuffer = buffer.getSamples();
} }
catch ( InterruptedException e ) catch(InterruptedException e)
{ {
mCurrentBuffer = null; mCurrentBuffer = null;
} }
@@ -273,47 +258,47 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
private float[] getSamples() private float[] getSamples()
{ {
int remaining = (int)mFFTFloatsPerFrame; int remaining = (int) mFFTFloatsPerFrame;
float[] currentFrame = new float[ remaining ]; float[] currentFrame = new float[remaining];
int currentFramePointer = 0; int currentFramePointer = 0;
float integralFloatsToConsume = mNewFloatsPerFrame + mNewFloatResidual; float integralFloatsToConsume = mNewFloatsPerFrame + mNewFloatResidual;
int newFloatsToConsumeThisFrame = (int)integralFloatsToConsume; int newFloatsToConsumeThisFrame = (int) integralFloatsToConsume;
mNewFloatResidual = integralFloatsToConsume - newFloatsToConsumeThisFrame; mNewFloatResidual = integralFloatsToConsume - newFloatsToConsumeThisFrame;
/* If the number of required floats for the fft is greater than the /* If the number of required floats for the fft is greater than the
* consumption rate per frame, we have to reach into the previous * consumption rate per frame, we have to reach into the previous
* frame to makeup the difference. */ * frame to makeup the difference. */
if( newFloatsToConsumeThisFrame < remaining ) if(newFloatsToConsumeThisFrame < remaining)
{ {
int previousFloatsRequired = remaining - newFloatsToConsumeThisFrame; int previousFloatsRequired = remaining - newFloatsToConsumeThisFrame;
System.arraycopy( mPreviousFrame, System.arraycopy(mPreviousFrame,
mPreviousFrame.length - previousFloatsRequired, mPreviousFrame.length - previousFloatsRequired,
currentFrame, currentFrame,
currentFramePointer, currentFramePointer,
previousFloatsRequired ); previousFloatsRequired);
remaining -= previousFloatsRequired; remaining -= previousFloatsRequired;
currentFramePointer += previousFloatsRequired; currentFramePointer += previousFloatsRequired;
} }
/* Fill the rest of the buffer with new samples */ /* Fill the rest of the buffer with new samples */
while( mRunning.get() && remaining > 0 ) while(mRunning.get() && remaining > 0)
{ {
if( mCurrentBuffer == null || if(mCurrentBuffer == null ||
mCurrentBufferPointer >= mCurrentBuffer.length ) mCurrentBufferPointer >= mCurrentBuffer.length)
{ {
getNextBuffer(); getNextBuffer();
} }
/* If we don't have new samples to use, send the current frame with /* If we don't have new samples to use, send the current frame with
* the remaining values as zero */ * the remaining values as zero */
if( mCurrentBuffer == null ) if(mCurrentBuffer == null)
{ {
remaining = 0; remaining = 0;
} }
@@ -321,10 +306,10 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
{ {
int samplesAvailable = mCurrentBuffer.length - mCurrentBufferPointer; int samplesAvailable = mCurrentBuffer.length - mCurrentBufferPointer;
while( remaining > 0 && samplesAvailable > 0 ) while(remaining > 0 && samplesAvailable > 0)
{ {
currentFrame[ currentFramePointer++ ] = currentFrame[currentFramePointer++] =
(float)mCurrentBuffer[ mCurrentBufferPointer++ ]; (float) mCurrentBuffer[mCurrentBufferPointer++];
samplesAvailable--; samplesAvailable--;
remaining--; remaining--;
@@ -336,13 +321,13 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
/* If the incoming float rate is greater than the fft consumption rate, /* If the incoming float rate is greater than the fft consumption rate,
* then we have to purge some floats, otherwise, store the previous * then we have to purge some floats, otherwise, store the previous
* frame, because we have overlapping frames */ * frame, because we have overlapping frames */
if( newFloatsToConsumeThisFrame > 0 ) if(newFloatsToConsumeThisFrame > 0)
{ {
purge( newFloatsToConsumeThisFrame ); purge(newFloatsToConsumeThisFrame);
} }
else else
{ {
mPreviousFrame = Arrays.copyOf( currentFrame, currentFrame.length ); mPreviousFrame = Arrays.copyOf(currentFrame, currentFrame.length);
} }
return currentFrame; return currentFrame;
@@ -352,42 +337,42 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
{ {
float[] samples = getSamples(); float[] samples = getSamples();
Window.apply( mWindow, samples ); Window.apply(mWindow, samples);
if( mSampleType == SampleType.REAL ) if(mSampleType == SampleType.REAL)
{ {
mFFT.realForward( samples ); mFFT.realForward(samples);
} }
else else
{ {
mFFT.complexForward( samples ); mFFT.complexForward(samples);
} }
dispatch( samples ); dispatch(samples);
} }
private void purge( int samplesToPurge ) private void purge(int samplesToPurge)
{ {
if( samplesToPurge <= 0 ) if(samplesToPurge <= 0)
{ {
throw new IllegalArgumentException( "DFTProcessor - cannot purge " throw new IllegalArgumentException("DFTProcessor - cannot purge "
+ "negative sample amount" ); + "negative sample amount");
} }
while( mRunning.get() && samplesToPurge > 0 ) while(mRunning.get() && samplesToPurge > 0)
{ {
if( mCurrentBuffer == null || if(mCurrentBuffer == null ||
mCurrentBufferPointer >= mCurrentBuffer.length ) mCurrentBufferPointer >= mCurrentBuffer.length)
{ {
getNextBuffer(); getNextBuffer();
} }
if( mCurrentBuffer != null ) if(mCurrentBuffer != null)
{ {
int samplesAvailable = mCurrentBuffer.length - mCurrentBufferPointer; int samplesAvailable = mCurrentBuffer.length - mCurrentBufferPointer;
if( samplesAvailable >= samplesToPurge ) if(samplesAvailable >= samplesToPurge)
{ {
mCurrentBufferPointer += samplesToPurge; mCurrentBufferPointer += samplesToPurge;
samplesToPurge = 0; samplesToPurge = 0;
@@ -409,24 +394,24 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
* Takes a calculated DFT results set, reformats the data, and sends it * Takes a calculated DFT results set, reformats the data, and sends it
* out to all registered listeners. * out to all registered listeners.
*/ */
private void dispatch( float[] results ) private void dispatch(float[] results)
{ {
Iterator<DFTResultsConverter> it = mListeners.iterator(); Iterator<DFTResultsConverter> it = mListeners.iterator();
while( it.hasNext() ) while(it.hasNext())
{ {
it.next().receive( results ); it.next().receive(results);
} }
} }
public void addConverter( DFTResultsConverter listener ) public void addConverter(DFTResultsConverter listener)
{ {
mListeners.add( listener ); mListeners.add(listener);
} }
public void removeConverter( DFTResultsConverter listener ) public void removeConverter(DFTResultsConverter listener)
{ {
mListeners.remove( listener ); mListeners.remove(listener);
} }
private class DFTCalculationTask implements Runnable private class DFTCalculationTask implements Runnable
@@ -437,18 +422,18 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
try try
{ {
/* Only run if we're not currently running */ /* Only run if we're not currently running */
if( mRunning.compareAndSet( false, true ) ) if(mRunning.compareAndSet(false, true))
{ {
checkFFTSize(); checkFFTSize();
calculate(); calculate();
mRunning.set( false ); mRunning.set(false);
} }
} }
catch( Exception e ) catch(Exception e)
{ {
mLog.error( "error during dft processor calculation task", e ); mLog.error("error during dft processor calculation task", e);
} }
} }
} }
@@ -460,24 +445,24 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
*/ */
private void checkFFTSize() private void checkFFTSize()
{ {
if( mNewDFTSize.getSize() != mDFTSize.getSize() ) if(mNewDFTSize.getSize() != mDFTSize.getSize())
{ {
mDFTSize = mNewDFTSize; mDFTSize = mNewDFTSize;
calculateConsumptionRate(); calculateConsumptionRate();
setWindowType( mWindowType ); setWindowType(mWindowType);
if( mSampleType == SampleType.COMPLEX ) if(mSampleType == SampleType.COMPLEX)
{ {
mPreviousFrame = new float[ mDFTSize.getSize() * 2 ]; mPreviousFrame = new float[mDFTSize.getSize() * 2];
} }
else else
{ {
mPreviousFrame = new float[ mDFTSize.getSize() ]; mPreviousFrame = new float[mDFTSize.getSize()];
} }
mFFT = new FloatFFT_1D( mDFTSize.getSize() ); mFFT = new FloatFFT_1D(mDFTSize.getSize());
} }
} }
@@ -487,9 +472,9 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
} }
@Override @Override
public void frequencyChanged( FrequencyChangeEvent event ) public void frequencyChanged(FrequencyChangeEvent event)
{ {
switch( event.getEvent() ) switch(event.getEvent())
{ {
case NOTIFICATION_SAMPLE_RATE_CHANGE: case NOTIFICATION_SAMPLE_RATE_CHANGE:
mSampleRate = event.getValue().intValue(); mSampleRate = event.getValue().intValue();
@@ -507,11 +492,11 @@ public class DFTProcessor implements Listener<ComplexBuffer>,
{ {
mNewFloatResidual = 0.0f; mNewFloatResidual = 0.0f;
mNewFloatsPerFrame = ( (float)mSampleRate / (float)mFrameRate ) * mNewFloatsPerFrame = ((float) mSampleRate / (float) mFrameRate) *
( mSampleType == SampleType.COMPLEX ? 2.0f : 1.0f ); (mSampleType == SampleType.COMPLEX ? 2.0f : 1.0f);
mFFTFloatsPerFrame = ( mSampleType == SampleType.COMPLEX ? mFFTFloatsPerFrame = (mSampleType == SampleType.COMPLEX ?
mDFTSize.getSize() * 2 : mDFTSize.getSize() * 2 :
mDFTSize.getSize() ); mDFTSize.getSize());
} }
} }

File diff suppressed because it is too large Load Diff