From c7830f6f0521b4f5f7c5dc21139f5e26992917ba Mon Sep 17 00:00:00 2001
From: Jonas Kvinge <jonas@jkvinge.net>
Date: Tue, 7 Jan 2025 01:09:49 +0100
Subject: [PATCH] MoodbarPipeline: Cleanup on finish

---
 src/moodbar/moodbarpipeline.cpp | 19 ++++++++++++++++++-
 src/moodbar/moodbarpipeline.h   |  4 ++--
 2 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/src/moodbar/moodbarpipeline.cpp b/src/moodbar/moodbarpipeline.cpp
index b710d2034..fc8723ef1 100644
--- a/src/moodbar/moodbarpipeline.cpp
+++ b/src/moodbar/moodbarpipeline.cpp
@@ -90,6 +90,7 @@ QByteArray MoodbarPipeline::ToGstUrl(const QUrl &url) {
 
 void MoodbarPipeline::Start() {
 
+  Q_ASSERT(QThread::currentThread() == thread());
   Q_ASSERT(QThread::currentThread() != qApp->thread());
 
   Utilities::SetThreadIOPriority(Utilities::IoPriority::IOPRIO_CLASS_IDLE);
@@ -208,6 +209,8 @@ GstBusSyncReply MoodbarPipeline::BusCallbackSync(GstBus *bus, GstMessage *messag
 
   MoodbarPipeline *instance = reinterpret_cast<MoodbarPipeline*>(self);
 
+  if (!instance->running_) return GST_BUS_PASS;
+
   switch (GST_MESSAGE_TYPE(message)) {
     case GST_MESSAGE_EOS:
       instance->Stop(true);
@@ -228,13 +231,26 @@ GstBusSyncReply MoodbarPipeline::BusCallbackSync(GstBus *bus, GstMessage *messag
 
 void MoodbarPipeline::Stop(const bool success) {
 
-  success_ = success;
   running_ = false;
+
+  QMetaObject::invokeMethod(this, "Finish", Qt::QueuedConnection, Q_ARG(bool, success));
+
+}
+
+void MoodbarPipeline::Finish(const bool success) {
+
+  Q_ASSERT(QThread::currentThread() == thread());
+  Q_ASSERT(QThread::currentThread() != qApp->thread());
+
+  success_ = success;
+
   if (builder_) {
     data_ = builder_->Finish(1000);
     builder_.reset();
   }
 
+  Cleanup();
+
   Q_EMIT Finished(success);
 
 }
@@ -242,6 +258,7 @@ void MoodbarPipeline::Stop(const bool success) {
 void MoodbarPipeline::Cleanup() {
 
   running_ = false;
+
   if (pipeline_) {
     GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline_));
     if (bus) {
diff --git a/src/moodbar/moodbarpipeline.h b/src/moodbar/moodbarpipeline.h
index ff9923c2b..3a15f02e9 100644
--- a/src/moodbar/moodbarpipeline.h
+++ b/src/moodbar/moodbarpipeline.h
@@ -47,8 +47,7 @@ class MoodbarPipeline : public QObject {
   bool success() const { return success_; }
   const QByteArray &data() const { return data_; }
 
- public Q_SLOTS:
-  void Start();
+  Q_INVOKABLE void Start();
 
  Q_SIGNALS:
   void Finished(const bool success);
@@ -59,6 +58,7 @@ class MoodbarPipeline : public QObject {
   QByteArray ToGstUrl(const QUrl &url);
   void ReportError(GstMessage *msg);
   void Stop(const bool success);
+  Q_INVOKABLE void Finish(const bool success);
   void Cleanup();
 
   static void NewPadCallback(GstElement *element, GstPad *pad, gpointer self);