Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Fix AutoLipSync hang and cancellation

Anderson Prado8c16179a2e59
diff --git a/toonz/sources/toonz/autolipsyncpopup.cpp b/toonz/sources/toonz/autolipsyncpopup.cpp
index 5bf1b65df..602ebb8e5 100644
--- a/toonz/sources/toonz/autolipsyncpopup.cpp
+++ b/toonz/sources/toonz/autolipsyncpopup.cpp
@@ -191,6 +191,8 @@ AutoLipSyncPopup::AutoLipSyncPopup()
, m_childLevel(nullptr) // Initialize as nullptr
, m_playingSound(nullptr) // Initialize as nullptr
, m_deleteFile(false) // Initialize as false
+ , m_processRunning(false) // Initialize as false
+ , m_userCancelled(false) // Initialize as false
{
setWindowTitle(tr("Auto Lip Sync"));
setFixedWidth(860);
@@ -218,9 +220,13 @@ AutoLipSyncPopup::AutoLipSyncPopup()
m_rhubarb = new QProcess(this);
m_player = new QMediaPlayer(this);
- m_progressDialog =
- new DVGui::ProgressDialog("Analyzing audio...", "", 1, 100, this);
+
+ // Initialize progress dialog with cancel button
+ m_progressDialog = new DVGui::ProgressDialog(tr("Analyzing audio..."),
+ tr("Cancel"), 0, 100, this);
m_progressDialog->hide();
+ m_progressDialog->setWindowFlag(Qt::WindowCloseButtonHint,
+ false); // Remove X button
m_soundLevels = new QComboBox(this);
m_playButton = new QPushButton(tr(""), this);
@@ -438,6 +444,10 @@ AutoLipSyncPopup::AutoLipSyncPopup()
connect(&m_audioTimeout, &QTimer::timeout, this,
&AutoLipSyncPopup::onAudioTimeout);
+ // Connect progress dialog cancel signal
+ connect(m_progressDialog, &DVGui::ProgressDialog::canceled, this,
+ &AutoLipSyncPopup::onAnalysisCancelled);
+
m_rhubarbPath = "";
}
@@ -518,6 +528,10 @@ void AutoLipSyncPopup::showEvent(QShowEvent *event) {
m_childLevel = nullptr;
m_startAt->setValue(1);
+ // Reset process flags
+ m_processRunning = false;
+ m_userCancelled = false;
+
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentScene()->getScene()->getXsheet();
m_col = TTool::getApplication()->getCurrentColumn()->getColumnIndex();
@@ -572,7 +586,7 @@ void AutoLipSyncPopup::showEvent(QShowEvent *event) {
}
if (!m_levelFrameIds.empty()) {
- // Fill with first 10 frames or repeat the first one
+ // Fill with the first 10 frames or repeat the first one
for (int i = 0; i < 10; i++) {
if (i < static_cast<int>(m_levelFrameIds.size())) {
m_activeFrameIds.push_back(m_levelFrameIds[i]);
@@ -581,7 +595,7 @@ void AutoLipSyncPopup::showEvent(QShowEvent *event) {
}
}
} else {
- // Clear active frame ids if no level frames
+ // Clear active frame IDs if no level frames are available
m_activeFrameIds.clear();
m_activeFrameIds.resize(10, TFrameId());
}
@@ -606,7 +620,7 @@ void AutoLipSyncPopup::showEvent(QShowEvent *event) {
void AutoLipSyncPopup::hideEvent(QHideEvent *event) {
stopAllSound();
- // Clean up temporary audio file
+ // Delete temporary file only if the process has finished or was cancelled
if (m_deleteFile && !m_audioPath.isEmpty()) {
TFilePath fp(m_audioPath);
if (TSystem::doesExistFileOrLevel(fp)) {
@@ -623,6 +637,7 @@ void AutoLipSyncPopup::hideEvent(QHideEvent *event) {
// Call base class implementation
Dialog::hideEvent(event);
}
+
//-----------------------------------------------------------------------------
void AutoLipSyncPopup::refreshSoundLevels() {
@@ -951,37 +966,167 @@ void AutoLipSyncPopup::onApplyButton() {
return;
}
- runRhubarb();
+ // Reset process flags
+ m_processRunning = true;
+ m_userCancelled = false;
+ // Disconnect any previous connections to avoid multiple signals
+ m_rhubarb->disconnect(this);
+
+ // Connect signals for async processing
+ connect(m_rhubarb,
+ QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
+ &AutoLipSyncPopup::onRhubarbFinished);
+ connect(m_rhubarb, &QProcess::errorOccurred, this,
+ &AutoLipSyncPopup::onRhubarbError);
+
+ // Show progress dialog
+ m_progressDialog->setLabelText(tr("Analyzing audio..."));
+ m_progressDialog->setValue(0);
+ m_progressDialog->show();
+ m_progressDialog->raise();
+ m_progressDialog->activateWindow();
+
+ // Get timeout from preferences (default 600 seconds = 10 minutes)
int rhubarbTimeout = ThirdParty::getRhubarbTimeout();
+
+ // Start timer for timeout (respect user preference)
if (rhubarbTimeout > 0) {
- rhubarbTimeout *= 1000;
- } else {
- rhubarbTimeout = -1;
+ QTimer::singleShot(rhubarbTimeout * 1000, this, [this, rhubarbTimeout]() {
+ if (m_processRunning) {
+ DVGui::warning(tr("Rhubarb process timed out after %1 seconds. The "
+ "process may be stuck.")
+ .arg(rhubarbTimeout));
+ onAnalysisCancelled();
+ }
+ });
}
- bool finished = m_rhubarb->waitForFinished(rhubarbTimeout);
+ runRhubarb();
+
+ // waitForFinished() is NOT called here process is async
+}
+
+//-----------------------------------------------------------------------------
+// Slot called when Rhubarb process finishes
+void AutoLipSyncPopup::onRhubarbFinished(int exitCode,
+ QProcess::ExitStatus exitStatus) {
+ m_processRunning = false;
m_progressDialog->hide();
- if (!finished) {
- DVGui::warning(tr("Rhubarb process timed out."));
+ // If user cancelled, don't process results
+ if (m_userCancelled) {
+ cleanupAfterProcess();
return;
}
- QString results = m_rhubarb->readAllStandardError();
- results += m_rhubarb->readAllStandardOutput();
- m_rhubarb->close();
-
- if (m_rhubarb->exitStatus() == QProcess::NormalExit) {
- int exitCode = m_rhubarb->exitCode();
- // onOuputReady will handle displaying any error messages from rhubarb
- if (exitCode != 0) return;
- } else {
+ if (exitStatus == QProcess::CrashExit) {
DVGui::warning(tr("Rhubarb process crashed."));
+ cleanupAfterProcess();
+ return;
+ }
+
+ if (exitCode != 0) {
+ // Error message should have been shown by onOutputReady
+ cleanupAfterProcess();
+ return;
+ }
+
+ // Process the results
+ processRhubarbResults();
+}
+
+//-----------------------------------------------------------------------------
+// Slot called when Rhubarb process has an error
+void AutoLipSyncPopup::onRhubarbError(QProcess::ProcessError error) {
+ m_processRunning = false;
+ m_progressDialog->hide();
+
+ // If the user cancelled, do not show an error — the "crash" was intentional
+ if (m_userCancelled) {
+ cleanupAfterProcess();
+ return;
+ }
+
+ // Only show an error if it was NOT an intentional cancellation
+ QString errorMsg;
+ switch (error) {
+ case QProcess::FailedToStart:
+ errorMsg = tr("Rhubarb failed to start. Check if the path is correct.");
+ break;
+ case QProcess::Crashed:
+ errorMsg = tr("Rhubarb crashed during execution.");
+ break;
+ case QProcess::Timedout:
+ errorMsg = tr("Rhubarb process timed out.");
+ break;
+ case QProcess::WriteError:
+ case QProcess::ReadError:
+ errorMsg = tr("Communication error with Rhubarb process.");
+ break;
+ default:
+ errorMsg = tr("Unknown error occurred with Rhubarb.");
+ }
+
+ DVGui::warning(errorMsg);
+ cleanupAfterProcess();
+}
+
+//-----------------------------------------------------------------------------
+// Slot called when user cancels analysis
+void AutoLipSyncPopup::onAnalysisCancelled() {
+ if (!m_processRunning) {
+ m_progressDialog->hide();
return;
}
- std::string strResults = results.toStdString();
+ // Mark that the user intentionally cancelled
+ m_userCancelled = true;
+
+ m_progressDialog->setLabelText(tr("Cancelling..."));
+ m_progressDialog->show();
+
+ if (m_rhubarb->state() == QProcess::Running) {
+ m_rhubarb->terminate();
+ if (!m_rhubarb->waitForFinished(2000)) {
+ m_rhubarb->kill();
+ m_rhubarb->waitForFinished(1000);
+ }
+ }
+
+ m_progressDialog->hide();
+ cleanupAfterProcess();
+}
+
+//-----------------------------------------------------------------------------
+// Clean up after process completion or cancellation
+void AutoLipSyncPopup::cleanupAfterProcess() {
+ m_processRunning = false;
+
+ // Clean temporary files
+ if (m_deleteFile && !m_audioPath.isEmpty()) {
+ TFilePath fp(m_audioPath);
+ if (TSystem::doesExistFileOrLevel(fp)) {
+ TSystem::deleteFile(fp);
+ }
+ }
+
+ // Clean dat file if exists
+ if (!m_datPath.isEmpty() && TSystem::doesExistFileOrLevel(m_datPath)) {
+ TSystem::deleteFile(m_datPath);
+ }
+
+ m_deleteFile = false;
+ m_progressDialog->hide();
+}
+
+//-----------------------------------------------------------------------------
+// Process Rhubarb results after successful completion
+void AutoLipSyncPopup::processRhubarbResults() {
+ QString results = m_rhubarb->readAllStandardError();
+ results += m_rhubarb->readAllStandardOutput();
+ m_rhubarb->close();
+
m_startAt->setValue(std::max(1, m_startFrame));
m_valid = false;
@@ -990,6 +1135,7 @@ void AutoLipSyncPopup::onApplyButton() {
QString path = m_datPath.getQString();
if (path.isEmpty()) {
DVGui::warning(tr("Please choose a lip sync data file to continue."));
+ cleanupAfterProcess();
return;
}
@@ -1001,12 +1147,14 @@ void AutoLipSyncPopup::onApplyButton() {
DVGui::warning(
tr("Cannot find the file specified. \nPlease choose a valid lip sync "
"data file to continue."));
+ cleanupAfterProcess();
return;
}
QFile file(tempPath.getQString());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
DVGui::warning(tr("Unable to open the file: \n") + file.errorString());
+ cleanupAfterProcess();
return;
}
@@ -1030,12 +1178,14 @@ void AutoLipSyncPopup::onApplyButton() {
tr("Invalid data file.\n Please choose a valid lip sync data file to "
"continue."));
m_valid = false;
+ cleanupAfterProcess();
return;
} else {
m_valid = true;
}
if (!m_valid || (!m_sl && !m_cl)) {
+ cleanupAfterProcess();
hide();
return;
}
@@ -1077,6 +1227,8 @@ void AutoLipSyncPopup::onApplyButton() {
TUndoManager::manager()->add(undo);
undo->redo();
+
+ cleanupAfterProcess();
hide();
}
@@ -1144,11 +1296,17 @@ void AutoLipSyncPopup::onStartValueChanged() {
AutoLipSyncPopup::~AutoLipSyncPopup() {
// Cleanup resources
stopAllSound();
- if (m_rhubarb && m_rhubarb->state() == QProcess::Running) {
- m_rhubarb->terminate();
+
+ // Kill any running process
+ if (m_processRunning && m_rhubarb->state() == QProcess::Running) {
+ m_rhubarb->kill();
m_rhubarb->waitForFinished(1000);
}
- // clear date
+
+ // Clean up temporary files
+ cleanupAfterProcess();
+
+ // Clear data
m_activeFrameIds.clear();
m_levelFrameIds.clear();
m_textLines.clear();
diff --git a/toonz/sources/toonz/autolipsyncpopup.h b/toonz/sources/toonz/autolipsyncpopup.h
index ef1f81fd8..8b39f7592 100644
--- a/toonz/sources/toonz/autolipsyncpopup.h
+++ b/toonz/sources/toonz/autolipsyncpopup.h
@@ -10,6 +10,7 @@
#include "toonzqt/gutil.h"
#include "toonz/txshsoundcolumn.h"
+#include <QProcess>
#include <QPushButton>
#include <QLabel>
#include <QCheckBox>
@@ -38,6 +39,7 @@ class QPaintEvent;
class AutoLipSyncPopup final : public DVGui::Dialog {
Q_OBJECT
+ // UI Elements
QLabel *m_aiLabel;
QLabel *m_oLabel;
QLabel *m_eLabel;
@@ -58,6 +60,8 @@ class AutoLipSyncPopup final : public DVGui::Dialog {
QPixmap m_pixmaps[10];
QPushButton *m_applyButton;
QPushButton *m_playButton;
+
+ // Level and frame data
std::vector<TFrameId> m_levelFrameIds;
std::vector<TFrameId> m_activeFrameIds;
DVGui::FileField *m_audioFile;
@@ -71,6 +75,8 @@ class AutoLipSyncPopup final : public DVGui::Dialog {
bool m_isEditingLevel;
QStringList m_textLines;
QCheckBox *m_restToEnd;
+
+ // Audio and processing
QString m_audioPath;
TFilePath m_datPath;
QMediaPlayer *m_player;
@@ -86,34 +92,59 @@ class AutoLipSyncPopup final : public DVGui::Dialog {
QTimer m_audioTimeout;
TXshSoundColumn *m_playingSound;
+ // Process management
+ bool m_processRunning; // Tracks if Rhubarb process is running
+ bool m_userCancelled; // Tracks if user cancelled the process
+
public:
AutoLipSyncPopup();
~AutoLipSyncPopup() override; // Added destructor
protected:
+ // Event handlers
void showEvent(QShowEvent *event) override;
void hideEvent(QHideEvent *event) override;
void paintEvent(QPaintEvent *event) override;
+
+ // UI helpers
void refreshSoundLevels();
+ void generateThumbnails();
+ void updateThumbnail(int index);
+
+ // Audio processing
void saveAudio();
void runRhubarb();
- // New function to generate thumbnails
- void generateThumbnails();
- void updateThumbnail(int index);
- void onIconGenerated();
+ // Process management
+ void cleanupAfterProcess(); // Cleans up temporary files and resets state
+ void processRhubarbResults(); // Processes successful Rhubarb output
public slots:
+ // Main actions
void onApplyButton();
- void imageNavClicked(int id);
- void onStartValueChanged();
void playSound();
void stopAllSound();
bool setAudioFile();
- void onLevelChanged(int);
+
+ // UI interactions
+ void imageNavClicked(int id);
+ void onStartValueChanged();
+ void onLevelChanged(int index);
+
+ // Media control
void onMediaStateChanged(QMediaPlayer::State state);
- void onOutputReady();
void onAudioTimeout();
+
+ // Rhubarb process handling
+ void onOutputReady();
+ void onRhubarbFinished(int exitCode, QProcess::ExitStatus exitStatus);
+ void onRhubarbError(QProcess::ProcessError error);
+ void onAnalysisCancelled(); // Called when user cancels analysis
+
+private slots:
+ // Internal slot for icon generation updates
+ void onIconGenerated(); // Called when IconGenerator finishes generating
+ // thumbnails
};
#endif // AUTOLIPSYNCPOPUP_H
diff --git a/toonz/sources/toonz/lipsyncpopup.h b/toonz/sources/toonz/lipsyncpopup.h
index 78649e42b..8f5ebc5cd 100644
--- a/toonz/sources/toonz/lipsyncpopup.h
+++ b/toonz/sources/toonz/lipsyncpopup.h
@@ -69,7 +69,10 @@ protected:
// Helper functions
void generateThumbnails();
void updateThumbnail(int index);
- void onIconGenerated();
+
+private slots:
+ // Internal slot for icon generation updates
+ void onIconGenerated(); // Called when IconGenerator finishes generating thumbnails
public slots:
void onApplyButton();
@@ -78,4 +81,4 @@ public slots:
void onStartValueChanged();
};
-#endif // LIPSYNCPOPUP_H
+#endif // LIPSYNCPOPUP_H
\ No newline at end of file