Browse Source

Add additional mutexs and don't block buddies for too long.

chirpmodem-v8.0.0
Jon Beniston 2 months ago
parent
commit
db492c59c7
  1. 18
      devices/usrp/deviceusrp.cpp
  2. 24
      devices/usrp/deviceusrpparam.cpp
  3. 101
      plugins/samplemimo/usrpmimo/usrpmimo.cpp
  4. 22
      plugins/samplemimo/usrpmimo/usrpmimo.h
  5. 15
      plugins/samplemimo/usrpmimo/usrpmimogui.cpp
  6. 5
      plugins/samplemimo/usrpmimo/usrpmimoworker.cpp
  7. 15
      plugins/samplemimo/usrpmimo/usrpmithread.cpp
  8. 122
      plugins/samplemimo/usrpmimo/usrpmothread.cpp
  9. 9
      plugins/samplemimo/usrpmimo/usrpmothread.h
  10. 73
      plugins/samplesink/usrpoutput/usrpoutput.cpp
  11. 3
      plugins/samplesink/usrpoutput/usrpoutput.h
  12. 35
      plugins/samplesink/usrpoutput/usrpoutputthread.cpp
  13. 8
      plugins/samplesink/usrpoutput/usrpoutputthread.h
  14. 73
      plugins/samplesource/usrpinput/usrpinput.cpp
  15. 3
      plugins/samplesource/usrpinput/usrpinput.h
  16. 43
      plugins/samplesource/usrpinput/usrpinputthread.cpp
  17. 7
      plugins/samplesource/usrpinput/usrpinputthread.h

18
devices/usrp/deviceusrp.cpp

@ -58,7 +58,7 @@ void DeviceUSRP::enumOriginDevices(const QString& hardwareId, PluginInterface::O @@ -58,7 +58,7 @@ void DeviceUSRP::enumOriginDevices(const QString& hardwareId, PluginInterface::O
// Opening some devices can be a little slow, so use hardcoded number of channels,
// for known devices
static const QMap<QString, int> channelMap{{"B200", 1}, {"B205", 1}, {"B200mini", 1}, {"B205mini", 1}, {"B210", 2}};
static const QMap<QString, int> channelMap{{"B200", 1}, {"B205", 1}, {"B200mini", 1}, {"B205mini", 1}, {"B206mini", 1}, {"B210", 2}};
if (channelMap.contains(product))
{
originDevices.append(PluginInterface::OriginDevice(
@ -264,10 +264,20 @@ bool DeviceUSRP::setMasterClockRateForSampleRate(uhd::usrp::multi_usrp::sptr usr @@ -264,10 +264,20 @@ bool DeviceUSRP::setMasterClockRateForSampleRate(uhd::usrp::multi_usrp::sptr usr
// as otherwise it could be changed when the first channel is set
properties->access<bool>(autoTickRatePath).set(false);
if (std::abs(usrp->get_master_clock_rate() - clockRate) >= 1.0)
try
{
if (std::abs(usrp->get_master_clock_rate() - clockRate) >= 1.0)
{
qDebug("DeviceUSRP::setMasterClockRateForSampleRate: setting master clock rate to %f for sample rate %f", clockRate, sampleRate);
usrp->set_master_clock_rate(clockRate);
}
}
catch (...)
{
qDebug("DeviceUSRP::setMasterClockRateForSampleRate: setting master clock rate to %f for sample rate %f", clockRate, sampleRate);
usrp->set_master_clock_rate(clockRate);
// Otherwise automatic selection would be left disabled, and as this function then sees it as manual,
// it would never be re-enabled
properties->access<bool>(autoTickRatePath).set(true);
throw;
}
return true;

24
devices/usrp/deviceusrpparam.cpp

@ -100,7 +100,11 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) @@ -100,7 +100,11 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly)
// tx/rx_rate is rate between PC and FPGA
uhd::meta_range_t clockRange = m_dev->get_master_clock_rate_range();
uhd::property_tree::sptr properties = m_dev->get_device()->get_tree();
if ((clockRange.start() == clockRange.stop()) || !properties->exists("/mboards/0/auto_tick_rate"))
const std::string autoTickRatePath = "/mboards/0/auto_tick_rate";
// If master_clock_rate was specified in the device args, it is fixed, so don't change it
if ((clockRange.start() == clockRange.stop())
|| !properties->exists(autoTickRatePath)
|| !properties->access<bool>(autoTickRatePath).get())
{
if (m_nbRxChannels > 0) {
m_srRangeRx = m_dev->get_rx_rates();
@ -117,6 +121,19 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) @@ -117,6 +121,19 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly)
}
else
{
// Setting the master clock rate disables automatic selection, so restore it afterwards,
// even if an exception is thrown, otherwise the clock rate would be stuck
struct RestoreAutoTickRate {
uhd::property_tree::sptr m_properties;
std::string m_path;
~RestoreAutoTickRate() {
try {
m_properties->access<bool>(m_path).set(true);
} catch (...) {
}
}
} restoreAutoTickRate{properties, autoTickRatePath};
// Find max and min sample rate, for max and min master clock rates
m_dev->set_master_clock_rate(clockRange.start());
uhd::meta_range_t rxLow;
@ -143,11 +160,6 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) @@ -143,11 +160,6 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly)
txHigh = m_dev->get_tx_rates();
m_srRangeTx = uhd::meta_range_t(std::min(txLow.start(), txHigh.start()), std::max(txLow.stop(), txHigh.stop()));
}
// Need to restore automatic clock rate
if (properties->exists("/mboards/0/auto_tick_rate")) {
properties->access<bool>("/mboards/0/auto_tick_rate").set(true);
}
}
});

101
plugins/samplemimo/usrpmimo/usrpmimo.cpp

@ -46,6 +46,7 @@ @@ -46,6 +46,7 @@
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgConfigureUSRPMIMO, Message)
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgStartStop, Message)
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgDeviceReconfigured, Message)
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgGetStreamInfo, Message)
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgReportStreamInfo, Message)
MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgGetDeviceInfo, Message)
@ -55,6 +56,7 @@ USRPMIMO::USRPMIMO(DeviceAPI *deviceAPI) : @@ -55,6 +56,7 @@ USRPMIMO::USRPMIMO(DeviceAPI *deviceAPI) :
m_settings(),
m_sourceThread(nullptr),
m_sinkThread(nullptr),
m_txRestartPending(false),
m_deviceDescription("USRPMIMO"),
m_runningRx(false),
m_runningTx(false),
@ -158,14 +160,11 @@ bool USRPMIMO::openDevice() @@ -158,14 +160,11 @@ bool USRPMIMO::openDevice()
void USRPMIMO::closeDevice()
{
// Stop Tx first, so stopRx doesn't pause and resume the Tx thread, which may be called from the GUI thread,
// while the device engine thread might be resizing the Tx FIFO
if (m_runningTx) {
stopTx();
}
if (m_runningRx) {
stopRx();
}
// while the device engine thread might be resizing the Tx FIFO.
// Call unconditionally, as they check m_runningTx/m_runningRx with m_mutex held, so wait for any start
// in progress in the device engine thread to complete
stopTx();
stopRx();
if (m_deviceParams)
{
@ -231,7 +230,12 @@ bool USRPMIMO::startRx() @@ -231,7 +230,12 @@ bool USRPMIMO::startRx()
for (int channel = 0; channel < m_nbRx; channel++)
{
device->set_rx_bandwidth(56000000, channel);
// Wide bandwidth while setting up the stream is not essential, so don't fail to create the stream if it can't be set
try {
device->set_rx_bandwidth(56000000, channel);
} catch (std::exception& e) {
qWarning() << "USRPMIMO::startRx: could not set bandwidth: " << e.what();
}
streamArgs.channels.push_back(channel);
}
@ -301,6 +305,13 @@ bool USRPMIMO::startTx() @@ -301,6 +305,13 @@ bool USRPMIMO::startTx()
}
qDebug("USRPMIMO::startTx");
{
// Device reconfigurations reported before we apply the settings below are covered by starting Tx,
// so only those reported after that need Tx to be restarted
QMutexLocker threadLocker(&m_threadMutex);
m_txRestartPending = false;
}
size_t bufSamples = 0;
USRPMIMOSettings settings;
@ -334,7 +345,12 @@ bool USRPMIMO::startTx() @@ -334,7 +345,12 @@ bool USRPMIMO::startTx()
for (int channel = 0; channel < m_nbTx; channel++)
{
device->set_tx_bandwidth(56000000, channel);
// Wide bandwidth while setting up the stream is not essential, so don't fail to create the stream if it can't be set
try {
device->set_tx_bandwidth(56000000, channel);
} catch (std::exception& e) {
qWarning() << "USRPMIMO::startTx: could not set bandwidth: " << e.what();
}
streamArgs.channels.push_back(channel);
}
@ -380,13 +396,21 @@ bool USRPMIMO::startTx() @@ -380,13 +396,21 @@ bool USRPMIMO::startTx()
QMutexLocker threadLocker(&m_threadMutex);
thread->setLog2Interpolation(m_settings.m_log2SoftInterp);
unsigned int fifoSize = getSampleMOFifoSize(m_settings);
if (fifoSize != getSampleMOFifoSize(settings)) {
// Resize in device engine thread once we return
m_sinkThread = thread;
// A device reconfiguration (that needs Tx to be restarted to realign channels) may have been reported
// while we were starting, before m_sinkThread was set, in which case it couldn't be acted upon
bool restart = m_txRestartPending;
m_txRestartPending = false;
// Allow settings to be changed while the FIFO is resized, as that can take a while
settingsLocker.unlock();
if ((fifoSize != getSampleMOFifoSize(settings)) || restart)
{
// As we're in the device engine thread, which the thread object belongs to, this is handled immediately,
// pausing streaming while the FIFO is resized. Keep the thread mutex locked, so a resize requested
// from the GUI thread (in resizeSampleMOFifo) can't be queued before this one, and so handled first
thread->getInputMessageQueue()->push(DeviceUSRPShared::MsgResizeSampleFifo::create(fifoSize));
}
m_sinkThread = thread;
}
m_runningTx = true;
@ -425,7 +449,11 @@ void USRPMIMO::stopRx() @@ -425,7 +449,11 @@ void USRPMIMO::stopRx()
m_sinkThread->stopWork();
}
m_rxStream = nullptr;
{
// Destroying the stream reconfigures the device, so prevent the worker applying settings at the same time
QMutexLocker deviceLocker(&m_deviceParams->m_mutex);
m_rxStream = nullptr;
}
if (txWasRunning) {
m_sinkThread->startWork();
@ -475,7 +503,11 @@ void USRPMIMO::stopTx() @@ -475,7 +503,11 @@ void USRPMIMO::stopTx()
m_sourceThread->stopWork();
}
m_txStream = nullptr;
{
// Destroying the stream reconfigures the device, so prevent the worker applying settings at the same time
QMutexLocker deviceLocker(&m_deviceParams->m_mutex);
m_txStream = nullptr;
}
if (rxWasRunning) {
m_sourceThread->startWork();
@ -484,6 +516,7 @@ void USRPMIMO::stopTx() @@ -484,6 +516,7 @@ void USRPMIMO::stopTx()
QByteArray USRPMIMO::serialize() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
return m_settings.serialize();
}
@ -520,24 +553,28 @@ const QString& USRPMIMO::getDeviceDescription() const @@ -520,24 +553,28 @@ const QString& USRPMIMO::getDeviceDescription() const
int USRPMIMO::getSourceSampleRate(int index) const
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
return m_settings.m_devSampleRate / (1<<m_settings.m_log2SoftDecim);
}
int USRPMIMO::getSinkSampleRate(int index) const
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
return m_settings.m_devSampleRate / (1<<m_settings.m_log2SoftInterp);
}
quint64 USRPMIMO::getSourceCenterFrequency(int index) const
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
return m_settings.m_rxCenterFrequency;
}
void USRPMIMO::setSourceCenterFrequency(qint64 centerFrequency, int index)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
USRPMIMOSettings settings = m_settings;
settings.m_rxCenterFrequency = centerFrequency;
@ -554,12 +591,14 @@ void USRPMIMO::setSourceCenterFrequency(qint64 centerFrequency, int index) @@ -554,12 +591,14 @@ void USRPMIMO::setSourceCenterFrequency(qint64 centerFrequency, int index)
quint64 USRPMIMO::getSinkCenterFrequency(int index) const
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
return m_settings.m_txCenterFrequency;
}
void USRPMIMO::setSinkCenterFrequency(qint64 centerFrequency, int index)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) index;
USRPMIMOSettings settings = m_settings;
settings.m_txCenterFrequency = centerFrequency;
@ -732,6 +771,21 @@ bool USRPMIMO::handleMessage(const Message& message) @@ -732,6 +771,21 @@ bool USRPMIMO::handleMessage(const Message& message)
return true;
}
else if (MsgDeviceReconfigured::match(message))
{
// Resize the FIFO for the new sample rate and restart Tx, so channels are realigned with a timed start.
// The resize stops and restarts Tx streaming in the device engine thread
QMutexLocker threadLocker(&m_threadMutex);
if (m_sinkThread) {
m_sinkThread->getInputMessageQueue()->push(DeviceUSRPShared::MsgResizeSampleFifo::create(getSampleMOFifoSize(m_settings)));
} else {
// Tx may be in the process of being started, in which case startTx will restart it once it has set m_sinkThread
m_txRestartPending = true;
}
return true;
}
else if (MsgGetStreamInfo::match(message))
{
if (m_guiMessageQueue)
@ -852,7 +906,11 @@ bool USRPMIMO::applySettings(const USRPMIMOSettings& settings, const QList<QStri @@ -852,7 +906,11 @@ bool USRPMIMO::applySettings(const USRPMIMOSettings& settings, const QList<QStri
m_settings.applySettings(settingsKeys, settings);
}
if (settingsKeys.contains("devSampleRate") || settingsKeys.contains("log2SoftInterp") || force) {
// When the sample rate or clock is changed, the worker sends MsgDeviceReconfigured once the device has been
// reconfigured, which resizes the FIFO (and restarts Tx), so only resize here if that won't happen
bool deviceReconfigured = settingsKeys.contains("devSampleRate") || settingsKeys.contains("clockSource") || force;
if (settingsKeys.contains("log2SoftInterp") && !deviceReconfigured) {
resizeSampleMOFifo();
}
@ -913,6 +971,7 @@ int USRPMIMO::webapiSettingsGet( @@ -913,6 +971,7 @@ int USRPMIMO::webapiSettingsGet(
SWGSDRangel::SWGDeviceSettings& response,
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
response.setUsrpMimoSettings(new SWGSDRangel::SWGUSRPMIMOSettings());
response.getUsrpMimoSettings()->init();
@ -926,6 +985,7 @@ int USRPMIMO::webapiSettingsPutPatch( @@ -926,6 +985,7 @@ int USRPMIMO::webapiSettingsPutPatch(
SWGSDRangel::SWGDeviceSettings& response, // query + response
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
USRPMIMOSettings settings = m_settings;
webapiUpdateDeviceSettings(settings, deviceSettingsKeys, response);
@ -1200,7 +1260,10 @@ void USRPMIMO::webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response) @@ -1200,7 +1260,10 @@ void USRPMIMO::webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response)
report->setTxDroppedPacketsCount(timeoutsDropped);
}
report->setMasterClockRate(m_settings.m_masterClockRate);
{
QMutexLocker settingsLocker(&m_settingsMutex);
report->setMasterClockRate(m_settings.m_masterClockRate);
}
// Don't block if settings are being applied to the device in another thread
if (m_deviceParams && m_deviceParams->getDevice() && m_deviceParams->m_mutex.tryLock())

22
plugins/samplemimo/usrpmimo/usrpmimo.h

@ -93,6 +93,25 @@ public: @@ -93,6 +93,25 @@ public:
{ }
};
/**
* Sent by the worker after applying settings that reconfigure the device's sample rate or clock,
* which can leave Tx channels misaligned, so Tx needs to be restarted with a timed start.
* (Rx detects misalignment itself, via ERROR_CODE_ALIGNMENT)
*/
class MsgDeviceReconfigured : public Message {
MESSAGE_CLASS_DECLARATION
public:
static MsgDeviceReconfigured* create() {
return new MsgDeviceReconfigured();
}
private:
MsgDeviceReconfigured() :
Message()
{ }
};
class MsgGetStreamInfo : public Message {
MESSAGE_CLASS_DECLARATION
@ -237,10 +256,11 @@ private: @@ -237,10 +256,11 @@ private:
DeviceAPI *m_deviceAPI;
QMutex m_mutex; //!< Serialises start and stop
QMutex m_threadMutex; //!< Protects thread pointers, for access from other threads
QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start
mutable QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread (start and getters) and web API threads
USRPMIMOSettings m_settings;
USRPMIThread* m_sourceThread;
USRPMOThread* m_sinkThread;
bool m_txRestartPending; //!< Tx needs restarting once m_sinkThread is set, as device was reconfigured while starting. Protected by m_threadMutex
QString m_deviceDescription;
bool m_runningRx;
bool m_runningTx;

15
plugins/samplemimo/usrpmimo/usrpmimogui.cpp

@ -706,13 +706,22 @@ void USRPMIMOGUI::on_decim_currentIndexChanged(int index) @@ -706,13 +706,22 @@ void USRPMIMOGUI::on_decim_currentIndexChanged(int index)
displaySampleRate();
int devSampleRate;
if (m_sampleRateMode) {
m_settings.m_devSampleRate = ui->sampleRate->getValueNew();
devSampleRate = ui->sampleRate->getValueNew();
} else {
m_settings.m_devSampleRate = ui->sampleRate->getValueNew() * (1 << index);
devSampleRate = ui->sampleRate->getValueNew() * (1 << index);
}
// Only send the device sample rate if it has changed, as setting it reconfigures the device
// and restarts Tx, which isn't needed if only the software decimation / interpolation has changed
if (devSampleRate != m_settings.m_devSampleRate)
{
m_settings.m_devSampleRate = devSampleRate;
m_settingsKeys.append("devSampleRate");
}
m_settingsKeys.append("devSampleRate");
sendSettings();
}

5
plugins/samplemimo/usrpmimo/usrpmimoworker.cpp

@ -86,6 +86,11 @@ void USRPMIMOWorker::handleInputMessages() @@ -86,6 +86,11 @@ void USRPMIMOWorker::handleInputMessages()
if (pendingConfig) {
applyDeviceSettings(m_deviceParams, m_nbRx, m_nbTx, settings, settingsKeys, force, true, true, true, true, m_reportQueue);
// Changing these reconfigures the device (E.g. resets the AD9361 on B2xx), which can misalign Tx channels
if (m_reportQueue && (force || settingsKeys.contains("devSampleRate") || settingsKeys.contains("clockSource"))) {
m_reportQueue->push(USRPMIMO::MsgDeviceReconfigured::create());
}
}
}

15
plugins/samplemimo/usrpmimo/usrpmithread.cpp

@ -72,7 +72,8 @@ void USRPMIThread::issueStreamCmd(bool start) @@ -72,7 +72,8 @@ void USRPMIThread::issueStreamCmd(bool start)
{
// Channels in a multi-channel stream need to be started at the same time, so they are aligned
streamCmd.stream_now = false;
streamCmd.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.05);
// Allow enough time for the command to reach the device, even if the device is being reconfigured
streamCmd.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.1);
}
else
{
@ -170,9 +171,12 @@ void USRPMIThread::run() @@ -170,9 +171,12 @@ void USRPMIThread::run()
// Higher priority, so streaming isn't delayed by other threads
DeviceUSRP::setStreamingThreadPriority();
// Hold mutex, so wake can't occur between startWork() checking m_runStarted and waiting
m_startWaitMutex.lock();
m_running = true;
m_runStarted = true;
m_startWaiter.wakeAll();
m_startWaitMutex.unlock();
try
{
@ -196,12 +200,15 @@ void USRPMIThread::run() @@ -196,12 +200,15 @@ void USRPMIThread::run()
{
m_overflows++;
}
else if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_ALIGNMENT)
else if ((md.error_code == uhd::rx_metadata_t::ERROR_CODE_ALIGNMENT)
|| (md.error_code == uhd::rx_metadata_t::ERROR_CODE_LATE_COMMAND))
{
// Channels lose alignment when the device is reconfigured while streaming
// (E.g. sample rate or clock source change, which resets the AD9361 on B2xx).
// UHD can't recover from this itself, so restart with a timed start to realign them
qDebug("USRPMIThread::run: multi-channel alignment failed - restarting");
// UHD can't recover from this itself, so restart with a timed start to realign them.
// If the timed start command arrived late, streaming won't have started, so also restart,
// rather than waiting for a timeout
qDebug() << "USRPMIThread::run:" << QString::fromStdString(md.strerror()) << "- restarting";
issueStreamCmd(false);
flush();
issueStreamCmd(true);

122
plugins/samplemimo/usrpmimo/usrpmothread.cpp

@ -17,6 +17,7 @@ @@ -17,6 +17,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <chrono>
#include <QDebug>
@ -35,6 +36,7 @@ USRPMOThread::USRPMOThread(uhd::usrp::multi_usrp::sptr device, uhd::tx_streamer: @@ -35,6 +36,7 @@ USRPMOThread::USRPMOThread(uhd::usrp::multi_usrp::sptr device, uhd::tx_streamer:
m_packets(0),
m_underflows(0),
m_droppedPackets(0),
m_lateStartPending(false),
m_device(device),
m_stream(stream),
m_bufSamples(bufSamples),
@ -72,6 +74,7 @@ void USRPMOThread::startWork() @@ -72,6 +74,7 @@ void USRPMOThread::startWork()
m_packets = 0;
m_underflows = 0;
m_droppedPackets = 0;
m_lateStartPending = false;
m_startWaitMutex.lock();
start();
@ -90,18 +93,9 @@ void USRPMOThread::stopWork() @@ -90,18 +93,9 @@ void USRPMOThread::stopWork()
}
m_running = false;
// run() ends the burst before exiting, so no underflow is reported when stopped,
// so we don't need to wait for and discard one here (which delayed pausing Tx)
wait();
try
{
// Get message indicating underflow, so it doesn't appear if we restart
uhd::async_metadata_t md;
m_stream->recv_async_msg(md);
}
catch (std::exception& e)
{
qDebug() << "USRPMOThread::stopWork: exception: " << e.what();
}
}
// Release references to stream and device, so they're destroyed when the device is closed,
@ -124,20 +118,32 @@ void USRPMOThread::handleInputMessages() @@ -124,20 +118,32 @@ void USRPMOThread::handleInputMessages()
{
QMutexLocker mutexLocker(&m_configMutex);
Message* message;
// Merge consecutive resize requests, so streaming is only stopped and restarted once,
// using the most recently requested size
bool resize = false;
unsigned int size = 0;
while ((message = m_inputMessageQueue.pop()) != nullptr)
{
if (!m_detached)
{
if (DeviceUSRPShared::MsgResizeSampleFifo::match(*message)) {
resizeSampleFifo(((const DeviceUSRPShared::MsgResizeSampleFifo&) *message).getSize());
} else {
if (DeviceUSRPShared::MsgResizeSampleFifo::match(*message))
{
resize = true;
size = ((const DeviceUSRPShared::MsgResizeSampleFifo&) *message).getSize();
}
else
{
qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier());
}
}
delete message;
}
if (resize) {
resizeSampleFifo(size);
}
}
// Resize the sample FIFO. This executes in the device engine thread, which writes to the FIFO,
@ -158,26 +164,21 @@ void USRPMOThread::resizeSampleFifo(unsigned int size) @@ -158,26 +164,21 @@ void USRPMOThread::resizeSampleFifo(unsigned int size)
}
}
void USRPMOThread::run()
// Start of burst at a time slightly in the future, so channels in a multi-channel stream start at the same time and are aligned
void USRPMOThread::setTimedStart(uhd::tx_metadata_t& md)
{
uhd::tx_metadata_t md;
md.end_of_burst = false;
// Higher priority, so streaming isn't delayed by other threads
DeviceUSRP::setStreamingThreadPriority();
if (m_nbChannels > 1)
{
// Channels in a multi-channel stream need to be started at the same time, so they are aligned
try
{
md.start_of_burst = true;
md.has_time_spec = true;
md.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.05);
// Allow enough time for the first packet to reach the device, even if the device is being reconfigured
md.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.1);
}
catch (std::exception& e)
{
qWarning() << "USRPMOThread::run: could not get time: " << e.what();
qWarning() << "USRPMOThread::setTimedStart: could not get time: " << e.what();
md.start_of_burst = false;
md.has_time_spec = false;
}
@ -187,12 +188,59 @@ void USRPMOThread::run() @@ -187,12 +188,59 @@ void USRPMOThread::run()
md.start_of_burst = false;
md.has_time_spec = false;
}
}
void USRPMOThread::run()
{
uhd::tx_metadata_t md;
md.end_of_burst = false;
// Higher priority, so streaming isn't delayed by other threads
DeviceUSRP::setStreamingThreadPriority();
setTimedStart(md);
// Hold mutex, so wake can't occur between startWork() checking m_running and waiting
m_startWaitMutex.lock();
m_running = true;
m_startWaiter.wakeAll();
m_startWaitMutex.unlock();
auto lastAsyncCheck = std::chrono::steady_clock::now();
while (m_running)
{
// Check for async messages periodically, rather than relying on getStreamStatus being called,
// so we can detect a late timed start of burst, after which the device may discard the burst
auto now = std::chrono::steady_clock::now();
if (now - lastAsyncCheck >= std::chrono::milliseconds(50))
{
lastAsyncCheck = now;
// getStreamStatus may also have seen a late start
bool lateStart = processAsyncMessages();
lateStart = m_lateStartPending.exchange(false) || lateStart;
if (lateStart && (m_nbChannels > 1))
{
qDebug("USRPMOThread::run: late start of burst - restarting");
try
{
md.end_of_burst = true;
m_stream->send(m_bufPtrs, 0, md);
}
catch (std::exception& e)
{
qDebug() << "USRPMOThread::run: exception sending end of burst: " << e.what();
}
md.end_of_burst = false;
setTimedStart(md);
}
}
unsigned int writtenSamples = callback();
try
@ -291,11 +339,15 @@ void USRPMOThread::callbackPart(unsigned int iBegin, unsigned int nSamples, unsi @@ -291,11 +339,15 @@ void USRPMOThread::callbackPart(unsigned int iBegin, unsigned int nSamples, unsi
}
// Called from GUI thread
void USRPMOThread::getStreamStatus(bool& active, quint32& underflows, quint32& droppedPackets)
// Drain pending async messages (without waiting) and update counters.
// Called from the streaming thread and from getStreamStatus in GUI / web API threads.
// Returns true if a packet arrived late (E.g. timed start of burst)
bool USRPMOThread::processAsyncMessages()
{
uhd::async_metadata_t md;
bool timeError = false;
QMutexLocker asyncMsgLocker(&m_asyncMsgMutex);
// Don't wait for messages (default timeout is 0.1s), and drain all pending messages
try
{
while (m_stream && m_stream->recv_async_msg(md, 0.0))
@ -308,11 +360,27 @@ void USRPMOThread::getStreamStatus(bool& active, quint32& underflows, quint32& d @@ -308,11 +360,27 @@ void USRPMOThread::getStreamStatus(bool& active, quint32& underflows, quint32& d
|| (md.event_code & uhd::async_metadata_t::EVENT_CODE_SEQ_ERROR_IN_BURST)) {
m_droppedPackets++;
}
if (md.event_code & uhd::async_metadata_t::EVENT_CODE_TIME_ERROR)
{
// Samples weren't transmitted, so count as an underflow
m_underflows++;
timeError = true;
}
}
}
catch (std::exception& e)
{
qDebug() << "USRPMOThread::getStreamStatus: exception: " << e.what();
qDebug() << "USRPMOThread::processAsyncMessages: exception: " << e.what();
}
return timeError;
}
void USRPMOThread::getStreamStatus(bool& active, quint32& underflows, quint32& droppedPackets)
{
// A late start of burst will be handled the next time the streaming thread checks
if (processAsyncMessages()) {
m_lateStartPending = true;
}
active = m_packets > 0;

9
plugins/samplemimo/usrpmimo/usrpmothread.h

@ -65,9 +65,12 @@ private: @@ -65,9 +65,12 @@ private:
QWaitCondition m_startWaiter;
std::atomic<bool> m_running;
// Counters are reset in startWork (device engine thread) and read in getStreamStatus (GUI / web API threads)
std::atomic<quint64> m_packets;
quint32 m_underflows;
quint32 m_droppedPackets;
std::atomic<quint32> m_underflows;
std::atomic<quint32> m_droppedPackets;
std::atomic<bool> m_lateStartPending; //!< Late start of burst seen in getStreamStatus, to be handled in run()
QMutex m_asyncMsgMutex; //!< Serialises recv_async_msg, which is called from different threads
uhd::usrp::multi_usrp::sptr m_device;
uhd::tx_streamer::sptr m_stream;
@ -86,6 +89,8 @@ private: @@ -86,6 +89,8 @@ private:
bool m_detached; //!< When set, no longer handle requests
void run();
void setTimedStart(uhd::tx_metadata_t& md);
bool processAsyncMessages();
unsigned int callback();
void callbackPart(unsigned int iBegin, unsigned int nSamples, unsigned int offset, unsigned int log2Interp);
void resizeSampleFifo(unsigned int size);

73
plugins/samplesink/usrpoutput/usrpoutput.cpp

@ -96,9 +96,11 @@ USRPOutput::~USRPOutput() @@ -96,9 +96,11 @@ USRPOutput::~USRPOutput()
);
delete m_networkManager;
if (m_running) {
stop();
}
// Call unconditionally, rather than checking m_running, as m_running is only set at the end of start(),
// which could still be running in the device engine thread. stop() checks m_running with m_mutex held,
// so waits for start() to complete. This must be done before the device mutex is locked below,
// as stop() locks the buddies mutex, which must be locked before the device mutex
stop();
DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams;
bool hasBuddies = (m_deviceAPI->getSourceBuddies().size() > 0) || (m_deviceAPI->getSinkBuddies().size() > 0);
@ -395,7 +397,7 @@ void USRPOutput::resumeTxBuddies() @@ -395,7 +397,7 @@ void USRPOutput::resumeTxBuddies()
void USRPOutput::closeDevice()
{
if (m_running) { stop(); }
// Already stopped in destructor, before the device mutex was locked
m_deviceShared.m_channel = -1; // effectively release the channel for the possible buddies
@ -439,7 +441,12 @@ bool USRPOutput::acquireChannel(const USRPOutputSettings& settings) @@ -439,7 +441,12 @@ bool USRPOutput::acquireChannel(const USRPOutputSettings& settings)
// However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage
// Actual settings are reported back to handleMessage, which forwards them to buddies and GUI
USRPOutputThread::applyDeviceSettings(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, settings, QList<QString>(), true, true, false, getInputMessageQueue());
usrp->set_tx_bandwidth(56000000, m_deviceShared.m_channel);
// Wide bandwidth while setting up the stream is not essential, so don't fail to create the stream if it can't be set
try {
usrp->set_tx_bandwidth(56000000, m_deviceShared.m_channel);
} catch (std::exception& e) {
qWarning() << "USRPOutput::acquireChannel: could not set bandwidth: " << e.what();
}
// set up the stream
std::string cpu_format("sc16");
@ -516,6 +523,14 @@ bool USRPOutput::start() @@ -516,6 +523,14 @@ bool USRPOutput::start()
return false;
}
// openDevice() can fail after the device params have been set, without a channel being allocated.
// UHD would treat channel -1 as all channels, which would reconfigure buddies' channels
if (m_deviceShared.m_channel < 0)
{
qCritical("USRPOutput::start: no channel allocated");
return false;
}
// Create thread before acquiring the channel, so settings changed while the channel is
// being acquired are queued to it, to be applied once start() has returned.
USRPOutputThread *thread = new USRPOutputThread(m_deviceShared.m_deviceParams, m_deviceShared.m_channel,
@ -537,6 +552,7 @@ bool USRPOutput::start() @@ -537,6 +552,7 @@ bool USRPOutput::start()
QMutexLocker threadLocker(&m_threadMutex);
m_usrpOutputThread = nullptr;
}
reapplyLostGPIO(thread);
delete thread;
return false;
}
@ -612,6 +628,7 @@ void USRPOutput::stop() @@ -612,6 +628,7 @@ void USRPOutput::stop()
// Release stream, so it's destroyed before the device, even if the thread is deleted later
thread->releaseStream();
reapplyLostGPIO(thread);
QThread *ownerThread = thread->thread();
if (!ownerThread || (ownerThread == QThread::currentThread()) || ownerThread->isFinished()) {
@ -626,8 +643,49 @@ void USRPOutput::stop() @@ -626,8 +643,49 @@ void USRPOutput::stop()
releaseChannel();
}
// When the thread exists, settings (including GPIO) are sent to it to be applied. If the thread is then deleted
// (failed start, or stopped) before handling them, they are lost. Other settings are applied when next started,
// but GPIO is also applied when not running, so if a GPIO change was lost, re-apply GPIO in the GUI thread,
// which will use the direct path, as the thread pointer has been cleared.
// Only do this if a change was actually lost, as Rx and Tx buddies share the same GPIO bank, so unnecessarily
// re-applying our settings could overwrite a buddy's.
// Must be called after the thread pointer has been cleared (so no more messages can be queued to the thread)
// and after the thread has been detached (or from the device engine thread, which the thread belongs to),
// so the thread can't be handling its messages. Not needed when called in the GUI thread, as we're being deleted.
void USRPOutput::reapplyLostGPIO(USRPOutputThread *thread)
{
if (QThread::currentThread() == this->thread()) {
return;
}
bool gpioLost = false;
Message *message;
while ((message = thread->getInputMessageQueue()->pop()) != nullptr)
{
if (MsgConfigureUSRP::match(*message))
{
const MsgConfigureUSRP& conf = (const MsgConfigureUSRP&) *message;
const QList<QString>& keys = conf.getSettingsKeys();
gpioLost = gpioLost || conf.getForce() || keys.contains("gpioDir") || keys.contains("gpioPins");
}
delete message;
}
if (gpioLost)
{
// Read the settings when this is handled in the GUI thread, rather than now, so settings changes queued
// to the GUI thread before this (E.g. from the web API) aren't overwritten with older values
QMetaObject::invokeMethod(this, [this]() {
m_inputMessageQueue.push(MsgConfigureUSRP::create(m_settings, QList<QString>{"gpioDir", "gpioPins"}, false));
}, Qt::QueuedConnection);
}
}
QByteArray USRPOutput::serialize() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
return m_settings.serialize();
}
@ -664,17 +722,20 @@ const QString& USRPOutput::getDeviceDescription() const @@ -664,17 +722,20 @@ const QString& USRPOutput::getDeviceDescription() const
int USRPOutput::getSampleRate() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
int rate = m_settings.m_devSampleRate;
return (rate / (1<<m_settings.m_log2SoftInterp));
}
quint64 USRPOutput::getCenterFrequency() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
return m_settings.m_centerFrequency;
}
void USRPOutput::setCenterFrequency(qint64 centerFrequency)
{
QMutexLocker settingsLocker(&m_settingsMutex);
USRPOutputSettings settings = m_settings;
settings.m_centerFrequency = centerFrequency;
@ -1253,6 +1314,7 @@ int USRPOutput::webapiSettingsGet( @@ -1253,6 +1314,7 @@ int USRPOutput::webapiSettingsGet(
SWGSDRangel::SWGDeviceSettings& response,
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
response.setUsrpOutputSettings(new SWGSDRangel::SWGUSRPOutputSettings());
response.getUsrpOutputSettings()->init();
@ -1266,6 +1328,7 @@ int USRPOutput::webapiSettingsPutPatch( @@ -1266,6 +1328,7 @@ int USRPOutput::webapiSettingsPutPatch(
SWGSDRangel::SWGDeviceSettings& response, // query + response
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
USRPOutputSettings settings = m_settings;
webapiUpdateDeviceSettings(settings, deviceSettingsKeys, response);

3
plugins/samplesink/usrpoutput/usrpoutput.h

@ -227,7 +227,7 @@ private: @@ -227,7 +227,7 @@ private:
QMutex m_mutex;
USRPOutputSettings m_settings;
USRPOutputThread* m_usrpOutputThread;
QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start()
mutable QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread (start() and getters) and web API threads
QMutex m_threadMutex; //!< Protects thread pointer, for access from threads other than the device engine thread
QString m_deviceDescription;
bool m_running;
@ -240,6 +240,7 @@ private: @@ -240,6 +240,7 @@ private:
bool openDevice();
void closeDevice();
void reapplyLostGPIO(USRPOutputThread *thread);
bool acquireChannel(const USRPOutputSettings& settings);
void releaseChannel();
DeviceUSRPParams *getBuddyDeviceParams() const;

35
plugins/samplesink/usrpoutput/usrpoutputthread.cpp

@ -97,23 +97,13 @@ void USRPOutputThread::startWork() @@ -97,23 +97,13 @@ void USRPOutputThread::startWork()
void USRPOutputThread::stopWork()
{
uhd::async_metadata_t md;
if (!m_running) return; // return if not running
m_running = false;
// run() ends the burst before exiting, so no underflow is reported when stopped,
// so we don't need to wait for and discard one here (which was done with the device mutex held)
wait();
try
{
// Get message indicating underflow, so it doesn't appear if we restart
m_stream->recv_async_msg(md);
}
catch (std::exception& e)
{
qDebug() << "USRPOutputThread::stopWork: exception: " << e.what();
}
qDebug("USRPOutputThread::stopWork: stream stopped");
}
@ -128,11 +118,15 @@ void USRPOutputThread::run() @@ -128,11 +118,15 @@ void USRPOutputThread::run()
// Higher priority, so streaming isn't delayed by other threads
DeviceUSRP::setStreamingThreadPriority();
md.start_of_burst = false;
// Start a new burst, which is ended when stopped, so the device doesn't report an underflow
md.start_of_burst = true;
md.end_of_burst = false;
// Hold mutex, so wake can't occur between startWork() checking m_running and waiting
m_startWaitMutex.lock();
m_running = true;
m_startWaiter.wakeAll();
m_startWaitMutex.unlock();
qDebug("USRPOutputThread::run");
@ -152,6 +146,19 @@ void USRPOutputThread::run() @@ -152,6 +146,19 @@ void USRPOutputThread::run()
{
qDebug() << "USRPOutputThread::run: exception: " << e.what();
}
md.start_of_burst = false;
}
// End the burst, so the stream can be restarted cleanly, without an underflow being reported
try
{
md.end_of_burst = true;
m_stream->send(m_buf, 0, md);
}
catch (std::exception& e)
{
qDebug() << "USRPOutputThread::run: exception sending end of burst: " << e.what();
}
m_running = false;
@ -234,6 +241,8 @@ void USRPOutputThread::getStreamStatus(bool& active, quint32& underflows, quint3 @@ -234,6 +241,8 @@ void USRPOutputThread::getStreamStatus(bool& active, quint32& underflows, quint3
// Don't wait for messages (default timeout is 0.1s), as this is called from the GUI thread
// Drain all pending messages, so counts are accurate
QMutexLocker asyncMsgLocker(&m_asyncMsgMutex);
try
{
while (m_stream->recv_async_msg(md, 0.0))

8
plugins/samplesink/usrpoutput/usrpoutputthread.h

@ -84,9 +84,11 @@ private: @@ -84,9 +84,11 @@ private:
QWaitCondition m_startWaiter;
std::atomic<bool> m_running;
quint64 m_packets;
quint32 m_underflows;
quint32 m_droppedPackets;
// Counters are reset in startWork (device engine threads) and read in getStreamStatus (GUI / web API threads)
std::atomic<quint64> m_packets;
std::atomic<quint32> m_underflows;
std::atomic<quint32> m_droppedPackets;
QMutex m_asyncMsgMutex; //!< Serialises recv_async_msg, which is called from different threads
uhd::tx_streamer::sptr m_stream;
qint16 *m_buf;

73
plugins/samplesource/usrpinput/usrpinput.cpp

@ -100,9 +100,11 @@ USRPInput::~USRPInput() @@ -100,9 +100,11 @@ USRPInput::~USRPInput()
);
delete m_networkManager;
if (m_running) {
stop();
}
// Call unconditionally, rather than checking m_running, as m_running is only set at the end of start(),
// which could still be running in the device engine thread. stop() checks m_running with m_mutex held,
// so waits for start() to complete. This must be done before the device mutex is locked below,
// as stop() locks the buddies mutex, which must be locked before the device mutex
stop();
DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams;
bool hasBuddies = (m_deviceAPI->getSourceBuddies().size() > 0) || (m_deviceAPI->getSinkBuddies().size() > 0);
@ -411,7 +413,7 @@ void USRPInput::resumeTxBuddies() @@ -411,7 +413,7 @@ void USRPInput::resumeTxBuddies()
void USRPInput::closeDevice()
{
if (m_running) { stop(); }
// Already stopped in destructor, before the device mutex was locked
m_deviceShared.m_channel = -1; // effectively release the channel for the possible buddies
@ -455,7 +457,12 @@ bool USRPInput::acquireChannel(const USRPInputSettings& settings) @@ -455,7 +457,12 @@ bool USRPInput::acquireChannel(const USRPInputSettings& settings)
// However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage
// Actual settings are reported back to handleMessage, which forwards them to buddies and GUI
USRPInputThread::applyDeviceSettings(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, settings, QList<QString>(), true, true, false, getInputMessageQueue());
usrp->set_rx_bandwidth(56000000, m_deviceShared.m_channel);
// Wide bandwidth while setting up the stream is not essential, so don't fail to create the stream if it can't be set
try {
usrp->set_rx_bandwidth(56000000, m_deviceShared.m_channel);
} catch (std::exception& e) {
qWarning() << "USRPInput::acquireChannel: could not set bandwidth: " << e.what();
}
// set up the stream
std::string cpu_format("sc16");
@ -534,6 +541,14 @@ bool USRPInput::start() @@ -534,6 +541,14 @@ bool USRPInput::start()
return false;
}
// openDevice() can fail after the device params have been set, without a channel being allocated.
// UHD would treat channel -1 as all channels, which would reconfigure buddies' channels
if (m_deviceShared.m_channel < 0)
{
qCritical("USRPInput::start: no channel allocated");
return false;
}
// Create thread before acquiring the channel, so settings changed while the channel is
// being acquired are queued to it, to be applied once start() has returned.
// start / stop streaming is done in the thread.
@ -556,6 +571,7 @@ bool USRPInput::start() @@ -556,6 +571,7 @@ bool USRPInput::start()
QMutexLocker threadLocker(&m_threadMutex);
m_usrpInputThread = nullptr;
}
reapplyLostGPIO(thread);
delete thread;
return false;
}
@ -615,6 +631,7 @@ void USRPInput::stop() @@ -615,6 +631,7 @@ void USRPInput::stop()
// Release stream, so it's destroyed before the device, even if the thread is deleted later
thread->releaseStream();
reapplyLostGPIO(thread);
QThread *ownerThread = thread->thread();
if (!ownerThread || (ownerThread == QThread::currentThread()) || ownerThread->isFinished()) {
@ -629,8 +646,49 @@ void USRPInput::stop() @@ -629,8 +646,49 @@ void USRPInput::stop()
releaseChannel();
}
// When the thread exists, settings (including GPIO) are sent to it to be applied. If the thread is then deleted
// (failed start, or stopped) before handling them, they are lost. Other settings are applied when next started,
// but GPIO is also applied when not running, so if a GPIO change was lost, re-apply GPIO in the GUI thread,
// which will use the direct path, as the thread pointer has been cleared.
// Only do this if a change was actually lost, as Rx and Tx buddies share the same GPIO bank, so unnecessarily
// re-applying our settings could overwrite a buddy's.
// Must be called after the thread pointer has been cleared (so no more messages can be queued to the thread)
// and after the thread has been detached (or from the device engine thread, which the thread belongs to),
// so the thread can't be handling its messages. Not needed when called in the GUI thread, as we're being deleted.
void USRPInput::reapplyLostGPIO(USRPInputThread *thread)
{
if (QThread::currentThread() == this->thread()) {
return;
}
bool gpioLost = false;
Message *message;
while ((message = thread->getInputMessageQueue()->pop()) != nullptr)
{
if (MsgConfigureUSRP::match(*message))
{
const MsgConfigureUSRP& conf = (const MsgConfigureUSRP&) *message;
const QList<QString>& keys = conf.getSettingsKeys();
gpioLost = gpioLost || conf.getForce() || keys.contains("gpioDir") || keys.contains("gpioPins");
}
delete message;
}
if (gpioLost)
{
// Read the settings when this is handled in the GUI thread, rather than now, so settings changes queued
// to the GUI thread before this (E.g. from the web API) aren't overwritten with older values
QMetaObject::invokeMethod(this, [this]() {
m_inputMessageQueue.push(MsgConfigureUSRP::create(m_settings, QList<QString>{"gpioDir", "gpioPins"}, false));
}, Qt::QueuedConnection);
}
}
QByteArray USRPInput::serialize() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
return m_settings.serialize();
}
@ -667,17 +725,20 @@ const QString& USRPInput::getDeviceDescription() const @@ -667,17 +725,20 @@ const QString& USRPInput::getDeviceDescription() const
int USRPInput::getSampleRate() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
int rate = m_settings.m_devSampleRate;
return (rate / (1<<m_settings.m_log2SoftDecim));
}
quint64 USRPInput::getCenterFrequency() const
{
QMutexLocker settingsLocker(&m_settingsMutex);
return m_settings.m_centerFrequency;
}
void USRPInput::setCenterFrequency(qint64 centerFrequency)
{
QMutexLocker settingsLocker(&m_settingsMutex);
USRPInputSettings settings = m_settings;
settings.m_centerFrequency = centerFrequency;
@ -1251,6 +1312,7 @@ int USRPInput::webapiSettingsGet( @@ -1251,6 +1312,7 @@ int USRPInput::webapiSettingsGet(
SWGSDRangel::SWGDeviceSettings& response,
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
response.setUsrpInputSettings(new SWGSDRangel::SWGUSRPInputSettings());
response.getUsrpInputSettings()->init();
@ -1264,6 +1326,7 @@ int USRPInput::webapiSettingsPutPatch( @@ -1264,6 +1326,7 @@ int USRPInput::webapiSettingsPutPatch(
SWGSDRangel::SWGDeviceSettings& response, // query + response
QString& errorMessage)
{
QMutexLocker settingsLocker(&m_settingsMutex);
(void) errorMessage;
USRPInputSettings settings = m_settings;
webapiUpdateDeviceSettings(settings, deviceSettingsKeys, response);

3
plugins/samplesource/usrpinput/usrpinput.h

@ -248,7 +248,7 @@ private: @@ -248,7 +248,7 @@ private:
QMutex m_mutex;
USRPInputSettings m_settings;
USRPInputThread* m_usrpInputThread;
QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start()
mutable QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread (start() and getters) and web API threads
QMutex m_threadMutex; //!< Protects thread pointer, for access from threads other than the device engine thread
QString m_deviceDescription;
bool m_running;
@ -262,6 +262,7 @@ private: @@ -262,6 +262,7 @@ private:
bool openDevice();
void closeDevice();
void reapplyLostGPIO(USRPInputThread *thread);
bool acquireChannel(const USRPInputSettings& settings);
void releaseChannel();
DeviceUSRPParams *getBuddyDeviceParams() const;

43
plugins/samplesource/usrpinput/usrpinputthread.cpp

@ -180,14 +180,42 @@ void USRPInputThread::stopWork() @@ -180,14 +180,42 @@ void USRPInputThread::stopWork()
// may need to be serialised (See DeviceUSRPRecvLock)
size_t USRPInputThread::recv(uhd::rx_metadata_t& md, double timeout)
{
if (m_deviceParams)
{
std::lock_guard<DeviceUSRPRecvLock> recvLock(m_deviceParams->m_recvLock);
if (!m_deviceParams) {
return m_stream->recv(m_buf, m_bufSamples, md, timeout);
}
else
// Only wait for a short time while holding the lock, so if our stream isn't receiving data
// (E.g. it's being restarted after a timeout), streams of buddies aren't blocked for long, which would cause them to overflow.
// The buffer is at most a few packets, so should be filled well within this time, at the sample rates where locking is used
const double maxLockedTimeout = 0.05;
double remaining = timeout;
while (true)
{
return m_stream->recv(m_buf, m_bufSamples, md, timeout);
const double lockedTimeout = std::min(remaining, maxLockedTimeout);
size_t samplesReceived;
{
std::lock_guard<DeviceUSRPRecvLock> recvLock(m_deviceParams->m_recvLock);
samplesReceived = m_stream->recv(m_buf, m_bufSamples, md, lockedTimeout);
}
if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
return samplesReceived;
}
if (samplesReceived > 0)
{
// Partially filled buffer: return what we have, rather than reporting a timeout, which would restart the stream
md.error_code = uhd::rx_metadata_t::ERROR_CODE_NONE;
return samplesReceived;
}
remaining -= lockedTimeout;
if (remaining <= 0.0) {
return samplesReceived; // Timed out
}
}
}
@ -203,9 +231,12 @@ void USRPInputThread::run() @@ -203,9 +231,12 @@ void USRPInputThread::run()
// Higher priority, so streaming isn't delayed by other threads
DeviceUSRP::setStreamingThreadPriority();
// Hold mutex, so wake can't occur between startWork() checking m_runStarted and waiting
m_startWaitMutex.lock();
m_running = true;
m_runStarted = true;
m_startWaiter.wakeAll();
m_startWaitMutex.unlock();
try
{
@ -217,7 +248,7 @@ void USRPInputThread::run() @@ -217,7 +248,7 @@ void USRPInputThread::run()
m_packets++;
if (samples_received != m_bufSamples)
{
qDebug("USRPInputThread::run - received %ld/%ld samples", samples_received, m_bufSamples);
qDebug("USRPInputThread::run - received %zu/%zu samples", samples_received, m_bufSamples);
}
if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT)
{

7
plugins/samplesource/usrpinput/usrpinputthread.h

@ -86,9 +86,10 @@ private: @@ -86,9 +86,10 @@ private:
std::atomic<bool> m_started; //!< Set from startWork() to stopWork()
std::atomic<bool> m_runStarted; //!< Set when run() has started
quint64 m_packets;
quint32 m_overflows;
quint32 m_timeouts;
// Counters are written in run(), reset in startWork (device engine threads) and read in getStreamStatus (GUI / web API threads)
std::atomic<quint64> m_packets;
std::atomic<quint32> m_overflows;
std::atomic<quint32> m_timeouts;
uhd::rx_streamer::sptr m_stream;
qint16 *m_buf;

Loading…
Cancel
Save