diff --git a/devices/usrp/deviceusrp.cpp b/devices/usrp/deviceusrp.cpp index af54450de..0887fcc7d 100644 --- a/devices/usrp/deviceusrp.cpp +++ b/devices/usrp/deviceusrp.cpp @@ -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 channelMap{{"B200", 1}, {"B205", 1}, {"B200mini", 1}, {"B205mini", 1}, {"B210", 2}}; + static const QMap 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 // as otherwise it could be changed when the first channel is set properties->access(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(autoTickRatePath).set(true); + throw; } return true; diff --git a/devices/usrp/deviceusrpparam.cpp b/devices/usrp/deviceusrpparam.cpp index 22f12376d..2fb2ab337 100644 --- a/devices/usrp/deviceusrpparam.cpp +++ b/devices/usrp/deviceusrpparam.cpp @@ -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(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) } 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(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) 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("/mboards/0/auto_tick_rate").set(true); - } } }); diff --git a/plugins/samplemimo/usrpmimo/usrpmimo.cpp b/plugins/samplemimo/usrpmimo/usrpmimo.cpp index aac1a25c8..7bcea9e3f 100644 --- a/plugins/samplemimo/usrpmimo/usrpmimo.cpp +++ b/plugins/samplemimo/usrpmimo/usrpmimo.cpp @@ -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) : 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() 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() 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() } 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() 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() 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() 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() 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() QByteArray USRPMIMO::serialize() const { + QMutexLocker settingsLocker(&m_settingsMutex); return m_settings.serialize(); } @@ -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<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 QListinit(); @@ -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) 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()) diff --git a/plugins/samplemimo/usrpmimo/usrpmimo.h b/plugins/samplemimo/usrpmimo/usrpmimo.h index 4c39ad107..2daab9594 100644 --- a/plugins/samplemimo/usrpmimo/usrpmimo.h +++ b/plugins/samplemimo/usrpmimo/usrpmimo.h @@ -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: 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; diff --git a/plugins/samplemimo/usrpmimo/usrpmimogui.cpp b/plugins/samplemimo/usrpmimo/usrpmimogui.cpp index 3554d0bbc..745d64bf6 100644 --- a/plugins/samplemimo/usrpmimo/usrpmimogui.cpp +++ b/plugins/samplemimo/usrpmimo/usrpmimogui.cpp @@ -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(); } diff --git a/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp b/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp index 39962b6d4..c7b35a65f 100644 --- a/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp +++ b/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp @@ -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()); + } } } diff --git a/plugins/samplemimo/usrpmimo/usrpmithread.cpp b/plugins/samplemimo/usrpmimo/usrpmithread.cpp index 34d9523a3..30e49ce4b 100644 --- a/plugins/samplemimo/usrpmimo/usrpmithread.cpp +++ b/plugins/samplemimo/usrpmimo/usrpmithread.cpp @@ -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() // 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() { 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); diff --git a/plugins/samplemimo/usrpmimo/usrpmothread.cpp b/plugins/samplemimo/usrpmimo/usrpmothread.cpp index f8b759d51..2ec934603 100644 --- a/plugins/samplemimo/usrpmimo/usrpmothread.cpp +++ b/plugins/samplemimo/usrpmimo/usrpmothread.cpp @@ -17,6 +17,7 @@ /////////////////////////////////////////////////////////////////////////////////// #include +#include #include @@ -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() m_packets = 0; m_underflows = 0; m_droppedPackets = 0; + m_lateStartPending = false; m_startWaitMutex.lock(); start(); @@ -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() { 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) } } -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() 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 } // 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 || (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; diff --git a/plugins/samplemimo/usrpmimo/usrpmothread.h b/plugins/samplemimo/usrpmimo/usrpmothread.h index 86e6cfecf..062d629b0 100644 --- a/plugins/samplemimo/usrpmimo/usrpmothread.h +++ b/plugins/samplemimo/usrpmimo/usrpmothread.h @@ -65,9 +65,12 @@ private: QWaitCondition m_startWaiter; std::atomic m_running; + // Counters are reset in startWork (device engine thread) and read in getStreamStatus (GUI / web API threads) std::atomic m_packets; - quint32 m_underflows; - quint32 m_droppedPackets; + std::atomic m_underflows; + std::atomic m_droppedPackets; + std::atomic 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: 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); diff --git a/plugins/samplesink/usrpoutput/usrpoutput.cpp b/plugins/samplesink/usrpoutput/usrpoutput.cpp index 826b9efd8..50acef1e8 100644 --- a/plugins/samplesink/usrpoutput/usrpoutput.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutput.cpp @@ -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() 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) // 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(), 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() 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() QMutexLocker threadLocker(&m_threadMutex); m_usrpOutputThread = nullptr; } + reapplyLostGPIO(thread); delete thread; return false; } @@ -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() 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& 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{"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 int USRPOutput::getSampleRate() const { + QMutexLocker settingsLocker(&m_settingsMutex); int rate = m_settings.m_devSampleRate; return (rate / (1<init(); @@ -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); diff --git a/plugins/samplesink/usrpoutput/usrpoutput.h b/plugins/samplesink/usrpoutput/usrpoutput.h index ef6b10703..0b201895e 100644 --- a/plugins/samplesink/usrpoutput/usrpoutput.h +++ b/plugins/samplesink/usrpoutput/usrpoutput.h @@ -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: bool openDevice(); void closeDevice(); + void reapplyLostGPIO(USRPOutputThread *thread); bool acquireChannel(const USRPOutputSettings& settings); void releaseChannel(); DeviceUSRPParams *getBuddyDeviceParams() const; diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp index 3a4de678f..caeb533f2 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp @@ -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() // 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() { 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 // 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)) diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.h b/plugins/samplesink/usrpoutput/usrpoutputthread.h index d87a4649f..487085a27 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.h +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.h @@ -84,9 +84,11 @@ private: QWaitCondition m_startWaiter; std::atomic 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 m_packets; + std::atomic m_underflows; + std::atomic m_droppedPackets; + QMutex m_asyncMsgMutex; //!< Serialises recv_async_msg, which is called from different threads uhd::tx_streamer::sptr m_stream; qint16 *m_buf; diff --git a/plugins/samplesource/usrpinput/usrpinput.cpp b/plugins/samplesource/usrpinput/usrpinput.cpp index 7dcff9af6..e279fc124 100644 --- a/plugins/samplesource/usrpinput/usrpinput.cpp +++ b/plugins/samplesource/usrpinput/usrpinput.cpp @@ -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() 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) // 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(), 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() 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() QMutexLocker threadLocker(&m_threadMutex); m_usrpInputThread = nullptr; } + reapplyLostGPIO(thread); delete thread; return false; } @@ -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() 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& 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{"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 int USRPInput::getSampleRate() const { + QMutexLocker settingsLocker(&m_settingsMutex); int rate = m_settings.m_devSampleRate; return (rate / (1<init(); @@ -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); diff --git a/plugins/samplesource/usrpinput/usrpinput.h b/plugins/samplesource/usrpinput/usrpinput.h index 2fbdf577a..04c662148 100644 --- a/plugins/samplesource/usrpinput/usrpinput.h +++ b/plugins/samplesource/usrpinput/usrpinput.h @@ -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: bool openDevice(); void closeDevice(); + void reapplyLostGPIO(USRPInputThread *thread); bool acquireChannel(const USRPInputSettings& settings); void releaseChannel(); DeviceUSRPParams *getBuddyDeviceParams() const; diff --git a/plugins/samplesource/usrpinput/usrpinputthread.cpp b/plugins/samplesource/usrpinput/usrpinputthread.cpp index 889b9e285..7a80c1f5a 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.cpp +++ b/plugins/samplesource/usrpinput/usrpinputthread.cpp @@ -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 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 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() // 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() 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) { diff --git a/plugins/samplesource/usrpinput/usrpinputthread.h b/plugins/samplesource/usrpinput/usrpinputthread.h index 6979dc380..65ed8e444 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.h +++ b/plugins/samplesource/usrpinput/usrpinputthread.h @@ -86,9 +86,10 @@ private: std::atomic m_started; //!< Set from startWork() to stopWork() std::atomic 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 m_packets; + std::atomic m_overflows; + std::atomic m_timeouts; uhd::rx_streamer::sptr m_stream; qint16 *m_buf;