]> git.sesse.net Git - kdenlive/blobdiff - src/projectlist.cpp
Fix some avformat producer concurrency crashes
[kdenlive] / src / projectlist.cpp
index ab15315760d8299502545b3249a10de68630f80b..2b0999539d55621a67033f08dce024fc68b5d169 100644 (file)
 #include <QHeaderView>
 #include <QInputDialog>
 #include <QtConcurrentRun>
+#include <QVBoxLayout>
+
+InvalidDialog::InvalidDialog(const QString &caption, const QString &message, bool infoOnly, QWidget *parent) : KDialog(parent)
+{
+    setCaption(caption);
+    if (infoOnly) setButtons(KDialog::Ok);
+    else setButtons(KDialog::Yes | KDialog::No);
+    QWidget *w = new QWidget(this);
+    QVBoxLayout *l = new QVBoxLayout;
+    l->addWidget(new QLabel(message));
+    m_clipList = new QListWidget;
+    l->addWidget(m_clipList);
+    w->setLayout(l);
+    setMainWidget(w);
+}
+
+InvalidDialog::~InvalidDialog()
+{
+    delete m_clipList;
+}
+
+
+void InvalidDialog::addClip(const QString &id, const QString &path)
+{
+    QListWidgetItem *item = new QListWidgetItem(path);
+    item->setData(Qt::UserRole, id);
+    m_clipList->addItem(item);
+}
+
+QStringList InvalidDialog::getIds() const
+{
+    QStringList ids;
+    for (int i = 0; i < m_clipList->count(); i++) {
+        ids << m_clipList->item(i)->data(Qt::UserRole).toString();
+    }
+    return ids;
+}
+
 
 ProjectList::ProjectList(QWidget *parent) :
     QWidget(parent),
@@ -77,8 +115,9 @@ ProjectList::ProjectList(QWidget *parent) :
     m_transcodeAction(NULL),
     m_doc(NULL),
     m_refreshed(false),
-    m_infoQueue(),
-    m_thumbnailQueue()
+    m_thumbnailQueue(),
+    m_abortAllProxies(false),
+    m_invalidClipDialog(NULL)
 {
     QVBoxLayout *layout = new QVBoxLayout;
     layout->setContentsMargins(0, 0, 0, 0);
@@ -90,6 +129,10 @@ ProjectList::ProjectList(QWidget *parent) :
     QHBoxLayout *box = new QHBoxLayout;
     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
 
+    m_refreshMonitorTimer.setSingleShot(true);
+    m_refreshMonitorTimer.setInterval(100);
+    connect(&m_refreshMonitorTimer, SIGNAL(timeout()), this, SLOT(slotRefreshMonitor()));
+
     box->addWidget(searchView);
     //int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
     //m_toolbar->setIconSize(QSize(s, s));
@@ -141,6 +184,8 @@ ProjectList::ProjectList(QWidget *parent) :
 
 ProjectList::~ProjectList()
 {
+    m_abortAllProxies = true;
+    m_thumbnailQueue.clear();
     delete m_menu;
     m_listView->blockSignals(true);
     m_listView->clear();
@@ -453,27 +498,35 @@ void ProjectList::slotReloadClip(const QString &id)
             continue;
         }
         item = static_cast <ProjectItem *>(selected.at(i));
-        if (item) {
+        if (item && !item->isProxyRunning()) {
+            DocClipBase *clip = item->referencedClip();
+            if (!clip->isClean()) {
+                // The clip is currently under processing (replacement in timeline), we cannot reload it now.
+                continue;
+            }
             CLIPTYPE t = item->clipType();
             if (t == TEXT) {
-                if (!item->referencedClip()->getProperty("xmltemplate").isEmpty())
+                if (clip && !clip->getProperty("xmltemplate").isEmpty())
                     regenerateTemplate(item);
-            } else if (t != COLOR && t != SLIDESHOW && item->referencedClip() &&  item->referencedClip()->checkHash() == false) {
+            } else if (t != COLOR && t != SLIDESHOW && clip && clip->checkHash() == false) {
                 item->referencedClip()->setPlaceHolder(true);
                 item->setProperty("file_hash", QString());
             } else if (t == IMAGE) {
-                item->referencedClip()->producer()->set("force_reload", 1);
+                clip->getProducer()->set("force_reload", 1);
             }
 
             QDomElement e = item->toXml();
             // Make sure we get the correct producer length if it was adjusted in timeline
             if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
-                int length = QString(item->referencedClip()->producerProperty("length")).toInt();
+                int length = QString(clip->producerProperty("length")).toInt();
                 if (length > 0 && !e.hasAttribute("length")) {
                     e.setAttribute("length", length);
                 }
-            }            
-            emit getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true, false);
+            }
+            if (clip) {
+                clip->clearThumbProducer();
+            }
+            m_render->getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true);
         }
     }
 }
@@ -519,9 +572,9 @@ void ProjectList::slotMissingClip(const QString &id)
                 return;
             }
             Mlt::Producer *newProd = m_render->invalidProducer(id);
-            if (item->referencedClip()->producer()) {
+            if (item->referencedClip()->getProducer()) {
                 Mlt::Properties props(newProd->get_properties());
-                Mlt::Properties src_props(item->referencedClip()->producer()->get_properties());
+                Mlt::Properties src_props(item->referencedClip()->getProducer()->get_properties());
                 props.inherit(src_props);
             }
             item->referencedClip()->setProducer(newProd, true);
@@ -574,29 +627,31 @@ void ProjectList::setRenderer(Render *projectRender)
 
 void ProjectList::slotClipSelected()
 {
-    if (!m_listView->isEnabled()) return;
-    if (m_listView->currentItem()) {
-        if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
+    m_refreshMonitorTimer.stop();
+    QTreeWidgetItem *item = m_listView->currentItem();
+    ProjectItem *clip = NULL;
+    if (item) {
+        if (item->type() == PROJECTFOLDERTYPE) {
             emit clipSelected(NULL);
-            m_editButton->defaultAction()->setEnabled(m_listView->currentItem()->childCount() > 0);
+            m_editButton->defaultAction()->setEnabled(item->childCount() > 0);
             m_deleteButton->defaultAction()->setEnabled(true);
             m_openAction->setEnabled(false);
             m_reloadAction->setEnabled(false);
             m_transcodeAction->setEnabled(false);
-            m_proxyAction->setEnabled(false);
         } else {
-            ProjectItem *clip;
-            if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
+            if (item->type() == PROJECTSUBCLIPTYPE) {
                 // this is a sub item, use base clip
                 m_deleteButton->defaultAction()->setEnabled(true);
-                clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
+                clip = static_cast <ProjectItem*>(item->parent());
                 if (clip == NULL) kDebug() << "-----------ERROR";
-                SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
+                SubProjectItem *sub = static_cast <SubProjectItem*>(item);
                 emit clipSelected(clip->referencedClip(), sub->zone());
                 m_transcodeAction->setEnabled(false);
+                m_reloadAction->setEnabled(false);
+                adjustProxyActions(clip);
                 return;
             }
-            clip = static_cast <ProjectItem*>(m_listView->currentItem());
+            clip = static_cast <ProjectItem*>(item);
             if (clip && clip->referencedClip())
                 emit clipSelected(clip->referencedClip());
             m_editButton->defaultAction()->setEnabled(true);
@@ -625,6 +680,7 @@ void ProjectList::slotClipSelected()
         m_reloadAction->setEnabled(false);
         m_transcodeAction->setEnabled(false);
     }
+    adjustProxyActions(clip);
 }
 
 void ProjectList::adjustProxyActions(ProjectItem *clip) const
@@ -791,6 +847,7 @@ void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
             clip = static_cast <ProjectItem*>(item->parent());
             m_transcodeAction->setEnabled(false);
+            adjustProxyActions(clip);
         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
             clip = static_cast <ProjectItem*>(item);
             // Display relevant transcoding actions only
@@ -877,7 +934,6 @@ void ProjectList::updateButtons() const
             m_openAction->setEnabled(true);
             m_reloadAction->setEnabled(true);
             m_transcodeAction->setEnabled(true);
-            m_proxyAction->setEnabled(useProxy());
             return;
         }
         else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) {
@@ -996,7 +1052,7 @@ void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
 
 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
 {
-    m_listView->setEnabled(false);
+    //m_listView->setEnabled(false);
     const QString parent = clip->getProperty("groupid");
     ProjectItem *item = NULL;
     monitorItemEditing(false);
@@ -1018,15 +1074,21 @@ void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
         item = new ProjectItem(m_listView, clip);
     }
     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
-    connect(clip, SIGNAL(createProxy(const QString)), this, SLOT(slotCreateProxy(const QString)));
-    connect(clip, SIGNAL(abortProxy(const QString, const QString)), this, SLOT(slotAbortProxy(const QString, const QString)));
+    QString proxy = clip->getProperty("proxy");
+    if (!proxy.isEmpty() && proxy != "-") slotCreateProxy(clip->getId());
+    connect(clip, SIGNAL(createProxy(const QString &)), this, SLOT(slotCreateProxy(const QString &)));
+    connect(clip, SIGNAL(abortProxy(const QString &, const QString &)), this, SLOT(slotAbortProxy(const QString, const QString)));
     if (getProperties) {
+        int height = m_listView->iconSize().height();
+        int width = (int)(height  * m_render->dar());
+        QPixmap pix =  KIcon("video-x-generic").pixmap(QSize(width, height));
+        item->setData(0, Qt::DecorationRole, pix);
+        //item->setFlags(Qt::ItemIsSelectable);
         m_listView->processLayout();
         QDomElement e = clip->toXML().cloneNode().toElement();
         e.removeAttribute("file_hash");
-        m_mutex.lock();
-        m_infoQueue.insert(clip->getId(), e);
-        m_mutex.unlock();
+        clip->clearThumbProducer();
+        m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
     }
     else if (item->hasProxy() && !item->isProxyRunning()) {
         slotCreateProxy(clip->getId());
@@ -1034,15 +1096,6 @@ void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
     clip->askForAudioThumbs();
     
     KUrl url = clip->fileURL();
-    if (getProperties == false && !clip->getClipHash().isEmpty()) {
-        QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
-        if (QFile::exists(cachedPixmap)) {
-            QPixmap pix(cachedPixmap);
-            if (pix.isNull())
-                KIO::NetAccess::del(KUrl(cachedPixmap), this);
-            item->setData(0, Qt::DecorationRole, pix);
-        }
-    }
 #ifdef NEPOMUK
     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
         // if file has Nepomuk comment, use it
@@ -1069,19 +1122,12 @@ void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
         }
     }
     monitorItemEditing(true);
-    if (m_listView->isEnabled()) {
-        updateButtons();
-    }
-    
-    //if (getProperties && m_processingClips.isEmpty())
-        //m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    if (getProperties)
-        QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
+    updateButtons();
 }
 
 void ProjectList::slotGotProxy(const QString &proxyPath)
 {
-    if (proxyPath.isEmpty() || !m_refreshed) return;
+    if (proxyPath.isEmpty() || !m_refreshed || m_abortAllProxies) return;
     QTreeWidgetItemIterator it(m_listView);
     ProjectItem *item;
 
@@ -1099,6 +1145,11 @@ void ProjectList::slotGotProxy(ProjectItem *item)
 {
     if (item == NULL || !m_refreshed) return;
     DocClipBase *clip = item->referencedClip();
+    if (!clip->isClean()) {
+        //WARNING: might result in clip said marked as proxy but not using proxy?
+        // The clip is currently under processing (replacement in timeline), we cannot reload it now.
+        return;
+    }
     // Proxy clip successfully created
     QDomElement e = clip->toXML().cloneNode().toElement();
 
@@ -1110,48 +1161,20 @@ void ProjectList::slotGotProxy(ProjectItem *item)
             e.setAttribute("length", length);
         }
     }
-    e.setAttribute("replace", 1);
-    m_mutex.lock();
-    m_infoQueue.insert(clip->getId(), e);
-    m_mutex.unlock();
-    //if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
+    clip->clearThumbProducer();
+    m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
 }
 
 void ProjectList::slotResetProjectList()
 {
+    m_abortAllProxies = true;
+    m_proxyThreads.waitForFinished();
+    m_proxyThreads.clearFutures();
+    m_thumbnailQueue.clear();
     m_listView->clear();
     emit clipSelected(NULL);
-    m_thumbnailQueue.clear();
-    m_infoQueue.clear();
     m_refreshed = false;
-}
-
-void ProjectList::slotProcessNextClipInQueue()
-{
-    if (m_infoQueue.isEmpty()) {
-        emit processNextThumbnail();
-        return;
-    }
-    QMutexLocker locker(&m_mutex);
-    QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
-    if (j != m_infoQueue.constEnd()) {
-        QDomElement dom = j.value().cloneNode().toElement();
-        const QString id = j.key();
-        m_infoQueue.remove(id);
-        m_processingClips.append(id);
-        locker.unlock();
-        bool replace;
-        if (dom.hasAttribute("replace")) {
-            // Proxy action was enabled / disabled and we want to replace current producer
-            dom.removeAttribute("replace");
-            replace = true;
-        }
-        else replace = false;
-        bool selectClip = !replace;
-        if (m_infoQueue.count() > 1) selectClip = false;
-        emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip);
-    }
+    m_abortAllProxies = false;
 }
 
 void ProjectList::slotUpdateClip(const QString &id)
@@ -1162,6 +1185,23 @@ void ProjectList::slotUpdateClip(const QString &id)
     monitorItemEditing(true);
 }
 
+void ProjectList::getCachedThumbnail(ProjectItem *item)
+{
+    if (!item) return;
+    DocClipBase *clip = item->referencedClip();
+    if (!clip) return;
+    QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
+    if (QFile::exists(cachedPixmap)) {
+        QPixmap pix(cachedPixmap);
+        if (pix.isNull()) {
+            KIO::NetAccess::del(KUrl(cachedPixmap), this);
+            requestClipThumbnail(item->clipId());
+        }
+        else item->setData(0, Qt::DecorationRole, pix);
+    }
+    else requestClipThumbnail(item->clipId());
+}
+
 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
 {
     m_listView->setSortingEnabled(false);
@@ -1196,7 +1236,7 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
         } else {
             item = static_cast <ProjectItem *>(*it);
             clip = item->referencedClip();
-            if (item->referencedClip()->producer() == NULL) {
+            if (item->referencedClip()->getProducer() == NULL) {
                 if (clip->isPlaceHolder() == false) {
                     QDomElement xml = clip->toXML();
                     if (fpsChanged) {
@@ -1204,10 +1244,9 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
                         xml.removeAttribute("file_hash");
                         xml.removeAttribute("proxy_out");
                     }
-                    m_mutex.lock();
-                    m_infoQueue.insert(clip->getId(), xml);
-                    m_mutex.unlock();
-                    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
+                    bool replace = xml.attribute("replace") == "1";
+                    if (replace) clip->clearThumbProducer();
+                    m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
                 }
                 else {
                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
@@ -1222,11 +1261,14 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
                         item->setData(0, Qt::DecorationRole, pixmap);
                     }
                 }
-            } else {
-                if (displayRatioChanged || item->data(0, Qt::DecorationRole).isNull())
+            } else {              
+                if (displayRatioChanged)
                     requestClipThumbnail(clip->getId());
+                else if (item->data(0, Qt::DecorationRole).isNull()) {
+                    getCachedThumbnail(item);
+                }
                 if (item->data(0, DurationRole).toString().isEmpty()) {
-                    item->changeDuration(item->referencedClip()->producer()->get_playtime());
+                    item->changeDuration(item->referencedClip()->getProducer()->get_playtime());
                 }
                 if (clip->isPlaceHolder()) {
                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
@@ -1245,16 +1287,9 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
         ++it;
     }
 
-    //if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    //QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    /*while (!m_infoQueue.isEmpty()) {
-        QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    }*/
-    
-    if (m_listView->isEnabled())
-        monitorItemEditing(true);
     m_listView->setSortingEnabled(true);
-    if (m_infoQueue.isEmpty()) {
+    if (m_render->processingItems() == 0) {
+       monitorItemEditing(true);
        slotProcessNextThumbnail();
     }
 }
@@ -1366,19 +1401,33 @@ void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
     ProjectItem *item = getItemById(id);
     m_processingClips.removeAll(id);
     m_thumbnailQueue.removeAll(id);
-    //if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);   
     if (item) {
+        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
         const QString path = item->referencedClip()->fileURL().path();
         if (item->referencedClip()->isPlaceHolder()) replace = false;
         if (!path.isEmpty()) {
+            if (m_invalidClipDialog) {
+                m_invalidClipDialog->addClip(id, path);
+                return;
+            }
+            else {
+                if (replace)
+                    m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", QString()), replace, kapp->activeWindow());
+                else {
+                    m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", QString()), replace, kapp->activeWindow());
+                }
+                m_invalidClipDialog->addClip(id, path);
+                int result = m_invalidClipDialog->exec();
+                if (result == KDialog::Yes) replace = true;
+            }
+        }
+        if (m_invalidClipDialog) {
             if (replace)
-                KMessageBox::sorry(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
-            else if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes)
-                replace = true;
+                emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
+            delete m_invalidClipDialog;
+            m_invalidClipDialog = NULL;
         }
-        if (replace)
-            emit deleteProjectClips(QStringList() << id, QMap <QString, QString>());
+        
     }
 }
 
@@ -1386,6 +1435,7 @@ void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
 {
     ProjectItem *item = getItemById(id);
     if (item) {
+        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
         if (durationError) {
             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2);
@@ -1401,8 +1451,6 @@ void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
     }
     m_processingClips.removeAll(id);
     m_thumbnailQueue.removeAll(id);
-    //if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
 }
 
 void ProjectList::slotAddColorClip()
@@ -1511,18 +1559,21 @@ QStringList ProjectList::getGroup() const
 void ProjectList::setDocument(KdenliveDoc *doc)
 {
     m_listView->blockSignals(true);
+    m_abortAllProxies = true;
+    m_proxyThreads.waitForFinished();
+    m_proxyThreads.clearFutures();
+    m_thumbnailQueue.clear();
     m_listView->clear();
     m_processingClips.clear();
+    
     m_listView->setSortingEnabled(false);
     emit clipSelected(NULL);
-    m_thumbnailQueue.clear();
-    m_infoQueue.clear();
     m_refreshed = false;
     m_fps = doc->fps();
     m_timecode = doc->timecode();
     m_commandStack = doc->commandStack();
     m_doc = doc;
-    setEnabled(!m_doc->isReadOnly());
+    m_abortAllProxies = false;
 
     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
     QStringList openedFolders = doc->getExpandedFolders();
@@ -1575,14 +1626,12 @@ QDomElement ProjectList::producersList()
 
 void ProjectList::slotCheckForEmptyQueue()
 {
-    if (m_processingClips.isEmpty() && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
+    if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
         if (!m_refreshed) {
             emit loadingIsOver();
             emit displayMessage(QString(), -1);
             m_refreshed = true;
         }
-        m_listView->blockSignals(false);
-        m_listView->setEnabled(true);
         updateButtons();
     } else if (!m_refreshed) {
         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
@@ -1593,22 +1642,20 @@ void ProjectList::slotCheckForEmptyQueue()
 void ProjectList::requestClipThumbnail(const QString id)
 {
     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
+    slotProcessNextThumbnail();
 }
 
 void ProjectList::slotProcessNextThumbnail()
 {
-    if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
-        slotCheckForEmptyQueue();
+    if (m_render->processingItems() > 0) {
         return;
     }
-    if (!m_infoQueue.isEmpty()) {
-        //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
+    if (m_thumbnailQueue.isEmpty()) {
+        slotCheckForEmptyQueue();
         return;
     }
-    if (m_thumbnailQueue.count() > 1) {
-        int max = m_doc->clipManager()->clipsCount();
-        emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
-    }
+    int max = m_doc->clipManager()->clipsCount();
+    emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
 }
 
@@ -1646,13 +1693,15 @@ void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
         }
         QPixmap pix;
         int height = m_listView->iconSize().height();
-        int width = (int)(height  * m_render->dar());
+        int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
+        int dwidth = (int)(height  * m_render->dar() + 0.5);
         if (clip->clipType() == AUDIO)
-            pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
+            pix = KIcon("audio-x-generic").pixmap(QSize(dwidth, height));
         else if (clip->clipType() == IMAGE)
-            pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
-        else
-            pix = item->referencedClip()->extractImage(frame, width, height);
+            pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height));
+        else {
+            pix = item->referencedClip()->extractImage(frame, dwidth, height);
+        }
 
         if (!pix.isNull()) {
             monitorItemEditing(false);
@@ -1670,33 +1719,45 @@ void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
     }
 }
 
-void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip)
+void ProjectList::slotRefreshMonitor()
+{
+    if (m_listView->selectedItems().count() == 1 && m_render && m_render->processingItems() == 0) {
+        if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE) {
+            ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
+            DocClipBase *clip = item->referencedClip();
+            if (clip && clip->isClean()) emit clipSelected(clip);
+        }
+    }
+}
+
+void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace, bool refreshThumbnail)
 {
     QString toReload;
     ProjectItem *item = getItemById(clipId);
-    if (!m_refreshed) {
-        // we are still finishing to load the document
-        selectClip = false;
+
+    int queue = m_render->processingItems();
+    if (queue == 0) {
+        m_listView->setEnabled(true);
     }
-    m_processingClips.removeAll(clipId);
-    if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true);
     if (item && producer) {
-        //m_listView->blockSignals(true);
         monitorItemEditing(false);
         DocClipBase *clip = item->referencedClip();
-        item->setProperties(properties, metadata);
-        if (clip->isPlaceHolder() && producer->is_valid()) {
-            clip->setValid();
+        if (producer->is_valid()) {
+            if (clip->isPlaceHolder()) {
+                clip->setValid();
+                toReload = clipId;
+            }
             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
-            toReload = clipId;
         }
         clip->setProducer(producer, replace);
+        item->setProperties(properties, metadata);
         clip->askForAudioThumbs();
+        if (refreshThumbnail) getCachedThumbnail(item);
         // Proxy stuff
         QString size = properties.value("frame_size");
         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
-        else if (useProxy() && !item->isProxyRunning()) {
+        else if (useProxy() && !item->hasProxy() && !item->isProxyRunning()) {
             // proxy video and image clips
             int maxSize;
             CLIPTYPE t = item->clipType();
@@ -1719,16 +1780,15 @@ void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Produce
             }
         }
 
-        if (!replace && item->data(0, Qt::DecorationRole).isNull())
+        if (!replace && item->data(0, Qt::DecorationRole).isNull() && !refreshThumbnail) {
             requestClipThumbnail(clipId);
+        }
         if (!toReload.isEmpty())
             item->slotSetToolTip();
-
-        if (m_listView->isEnabled())
-            monitorItemEditing(true);
     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
-    if (selectClip && m_infoQueue.isEmpty()) {
-        if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
+    if (queue == 0) {
+        monitorItemEditing(true);
+        if (item && m_thumbnailQueue.isEmpty()) {
             m_listView->setCurrentItem(item);
             bool updatedProfile = false;
             if (item->parent()) {
@@ -1738,24 +1798,28 @@ void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Produce
                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
                 updatedProfile = adjustProjectProfileToItem(item);
             }
-            if (updatedProfile == false) emit clipSelected(item->referencedClip());
+            if (updatedProfile == false) {
+                //emit clipSelected(item->referencedClip());
+            }
         } else {
             int max = m_doc->clipManager()->clipsCount();
-            emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
+            emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
         }
+        processNextThumbnail();
+    }
+    if (replace && item) {
+        if (item->numReferences() > 0) toReload = clipId;
+        else item->referencedClip()->cleanupProducers();
+        // update clip in clip monitor
+        if (queue == 0 && item->isSelected() && m_listView->selectedItems().count() == 1)
+            m_refreshMonitorTimer.start();
+    }
+    if (!item) {
+        // no item for producer, delete it
+        delete producer;
     }
-    if (item && m_listView->isEnabled() && replace) {
-            // update clip in clip monitor
-            if (item->isSelected() && m_listView->selectedItems().count() == 1)
-                emit clipSelected(item->referencedClip());
-            //TODO: Make sure the line below has no side effect
-            toReload = clipId;
-        }
     if (!toReload.isEmpty())
         emit clipNeedsReload(toReload, true);
-
-    //if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
 }
 
 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
@@ -1837,16 +1901,27 @@ bool ProjectList::generateImageProxy() const
     return m_doc->getDocumentProperty("generateimageproxy").toInt();
 }
 
-void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
+void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
+{
+    QPixmap pix = QPixmap::fromImage(img);
+    setThumbnail(clipId, pix);
+}
+
+void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
+{
+    QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
+    setThumbnail(clipId, pix);
+}
+
+void ProjectList::setThumbnail(const QString &clipId, const QPixmap &pix)
 {
     ProjectItem *item = getItemById(clipId);
     if (item && !pix.isNull()) {
         monitorItemEditing(false);
         item->setData(0, Qt::DecorationRole, pix);
         monitorItemEditing(true);
+        //update();
         m_doc->cachePixmap(item->getClipHash(), pix);
-        if (m_listView->isEnabled())
-            m_listView->blockSignals(false);
     }
 }
 
@@ -1928,7 +2003,6 @@ void ProjectList::slotSelectClip(const QString &ix)
         m_deleteButton->defaultAction()->setEnabled(true);
         m_reloadAction->setEnabled(true);
         m_transcodeAction->setEnabled(true);
-        m_proxyAction->setEnabled(useProxy());
         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
             m_openAction->setEnabled(true);
@@ -1994,7 +2068,7 @@ void ProjectList::regenerateTemplate(const QString &id)
 void ProjectList::regenerateTemplate(ProjectItem *clip)
 {
     //TODO: remove this unused method, only force_reload is necessary
-    clip->referencedClip()->producer()->set("force_reload", 1);
+    clip->referencedClip()->getProducer()->set("force_reload", 1);
 }
 
 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
@@ -2113,9 +2187,7 @@ void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const
 
 void ProjectList::slotForceProcessing(const QString &id)
 {
-    while (m_infoQueue.contains(id)) {
-        slotProcessNextClipInQueue();
-    }
+    m_render->forceProcessing(id);
 }
 
 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
@@ -2193,7 +2265,14 @@ void ProjectList::slotCreateProxy(const QString id)
         return;
     }
     m_processingProxy.append(path);
-    QtConcurrent::run(this, &ProjectList::slotGenerateProxy, path, item->clipUrl().path(), item->clipType(), QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt());
+
+    PROXYINFO info;
+    info.dest = path;
+    info.src = item->clipUrl().path();
+    info.type = item->clipType();
+    info.exif = QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt();
+    m_proxyList.append(info);
+    m_proxyThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotGenerateProxy));
 }
 
 void ProjectList::slotAbortProxy(const QString id, const QString path)
@@ -2208,27 +2287,34 @@ void ProjectList::slotAbortProxy(const QString id, const QString path)
     }
 }
 
-void ProjectList::slotGenerateProxy(const QString destPath, const QString sourcePath, int clipType, int exif_orientation)
+void ProjectList::slotGenerateProxy()
 {
+    if (m_proxyList.isEmpty() || m_abortAllProxies) return;
     emit projectModified();
+    PROXYINFO info = m_proxyList.takeFirst();
+    if (m_abortProxy.contains(info.dest)) {
+        m_abortProxy.removeAll(info.dest);
+        return;
+    }
+
     // Make sure proxy path is writable
-    QFile file(destPath);
+    QFile file(info.dest);
     if (!file.open(QIODevice::WriteOnly)) {
-        setProxyStatus(destPath, PROXYCRASHED);
-        m_processingProxy.removeAll(destPath);
+        setProxyStatus(info.dest, PROXYCRASHED);
+        m_processingProxy.removeAll(info.dest);
         return;
     }
     file.close();
-    QFile::remove(destPath);
+    QFile::remove(info.dest);
     
-    setProxyStatus(destPath, CREATINGPROXY);
+    setProxyStatus(info.dest, CREATINGPROXY);
 
     // Special case: playlist clips (.mlt or .kdenlive project files)
-    if (clipType == PLAYLIST) {
+    if (info.type == PLAYLIST) {
         // change FFmpeg params to MLT format
         QStringList parameters;
-        parameters << sourcePath;
-        parameters << "-consumer" << "avformat:" + destPath;
+        parameters << info.src;
+        parameters << "-consumer" << "avformat:" + info.dest;
         QStringList params = m_doc->getDocumentProperty("proxyparams").simplified().split('-', QString::SkipEmptyParts);
         
         foreach(QString s, params) {
@@ -2243,50 +2329,55 @@ void ProjectList::slotGenerateProxy(const QString destPath, const QString source
         parameters.append(QString("real_time=-%1").arg(KdenliveSettings::mltthreads()));
 
         //TODO: currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy
-        double display_ratio = KdenliveDoc::getDisplayRatio(sourcePath);
+        double display_ratio = KdenliveDoc::getDisplayRatio(info.src);
         parameters << "aspect=" + QString::number(display_ratio);
 
         //kDebug()<<"TRANSCOD: "<<parameters;
         QProcess myProcess;
+        myProcess.setProcessChannelMode(QProcess::MergedChannels);
         myProcess.start(KdenliveSettings::rendererpath(), parameters);
         myProcess.waitForStarted();
         int result = -1;
+        int duration = 0;
         while (myProcess.state() != QProcess::NotRunning) {
             // building proxy file
-            if (m_abortProxy.contains(destPath)) {
+            if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
                 myProcess.close();
                 myProcess.waitForFinished();
-                m_abortProxy.removeAll(destPath);
-                m_processingProxy.removeAll(destPath);
-                QFile::remove(destPath);
-                setProxyStatus(destPath, NOPROXY);
+                QFile::remove(info.dest);
+                m_abortProxy.removeAll(info.dest);
+                m_processingProxy.removeAll(info.dest);
+                setProxyStatus(info.dest, NOPROXY);
                 result = -2;
-
+            }
+            else {
+                QString log = QString(myProcess.readAll());
+                processLogInfo(info.dest, &duration, log);
             }
             myProcess.waitForFinished(500);
         }
         myProcess.waitForFinished();
-        m_processingProxy.removeAll(destPath);
+        m_processingProxy.removeAll(info.dest);
         if (result == -1) result = myProcess.exitStatus();
         if (result == 0) {
             // proxy successfully created
-            setProxyStatus(destPath, PROXYDONE);
-            slotGotProxy(destPath);
+            setProxyStatus(info.dest, PROXYDONE);
+            slotGotProxy(info.dest);
         }
         else if (result == 1) {
             // Proxy process crashed
-            QFile::remove(destPath);
-            setProxyStatus(destPath, PROXYCRASHED);
+            QFile::remove(info.dest);
+            setProxyStatus(info.dest, PROXYCRASHED);
         }   
 
     }
     
-    if (clipType == IMAGE) {
+    if (info.type == IMAGE) {
         // Image proxy
-        QImage i(sourcePath);
+        QImage i(info.src);
         if (i.isNull()) {
             // Cannot load image
-            setProxyStatus(destPath, PROXYCRASHED);
+            setProxyStatus(info.dest, PROXYCRASHED);
             return;
         }
         QImage proxy;
@@ -2294,12 +2385,12 @@ void ProjectList::slotGenerateProxy(const QString destPath, const QString source
         //TODO: Make it be configurable?
         if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth());
         else proxy = i.scaledToHeight(m_render->renderHeight());
-        if (exif_orientation > 1) {
+        if (info.exif > 1) {
             // Rotate image according to exif data
             QImage processed;
             QMatrix matrix;
 
-            switch ( exif_orientation ) {
+            switch ( info.exif ) {
                 case 2:
                   matrix.scale( -1, 1 );
                   break;
@@ -2325,58 +2416,86 @@ void ProjectList::slotGenerateProxy(const QString destPath, const QString source
                   break;
               }
               processed = proxy.transformed( matrix );
-              processed.save(destPath);
+              processed.save(info.dest);
         }
-        else proxy.save(destPath);
-        setProxyStatus(destPath, PROXYDONE);
-        slotGotProxy(destPath);
-        m_abortProxy.removeAll(destPath);
-        m_processingProxy.removeAll(destPath);
+        else proxy.save(info.dest);
+        setProxyStatus(info.dest, PROXYDONE);
+        slotGotProxy(info.dest);
+        m_abortProxy.removeAll(info.dest);
+        m_processingProxy.removeAll(info.dest);
         return;
     }
 
     QStringList parameters;
-    parameters << "-i" << sourcePath;
+    parameters << "-i" << info.src;
     QString params = m_doc->getDocumentProperty("proxyparams").simplified();
     foreach(QString s, params.split(' '))
     parameters << s;
 
     // Make sure we don't block when proxy file already exists
     parameters << "-y";
-    parameters << destPath;
+    parameters << info.dest;
     kDebug()<<"// STARTING PROXY GEN: "<<parameters;
     QProcess myProcess;
+    myProcess.setProcessChannelMode(QProcess::MergedChannels);
     myProcess.start("ffmpeg", parameters);
     myProcess.waitForStarted();
     int result = -1;
+    int duration = 0;
     while (myProcess.state() != QProcess::NotRunning) {
         // building proxy file
-        if (m_abortProxy.contains(destPath)) {
+        if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
             myProcess.close();
             myProcess.waitForFinished();
-            m_abortProxy.removeAll(destPath);
-            m_processingProxy.removeAll(destPath);
-            QFile::remove(destPath);
-            setProxyStatus(destPath, NOPROXY);
+            m_abortProxy.removeAll(info.dest);
+            m_processingProxy.removeAll(info.dest);
+            QFile::remove(info.dest);
+            setProxyStatus(info.dest, NOPROXY);
             result = -2;
             
         }
+        else {
+            QString log = QString(myProcess.readAll());
+            processLogInfo(info.dest, &duration, log);
+        }
         myProcess.waitForFinished(500);
     }
     myProcess.waitForFinished();
     if (result == -1) result = myProcess.exitStatus();
     if (result == 0) {
         // proxy successfully created
-        setProxyStatus(destPath, PROXYDONE);
-        slotGotProxy(destPath);
+        setProxyStatus(info.dest, PROXYDONE);
+        slotGotProxy(info.dest);
     }
     else if (result == 1) {
         // Proxy process crashed
-        QFile::remove(destPath);
-        setProxyStatus(destPath, PROXYCRASHED);
+        QFile::remove(info.dest);
+        setProxyStatus(info.dest, PROXYCRASHED);
+    }
+    m_abortProxy.removeAll(info.dest);
+    m_processingProxy.removeAll(info.dest);
+}
+
+
+void ProjectList::processLogInfo(const QString &path, int *duration, const QString &log)
+{
+    int progress;
+    if (*duration == 0) {
+        if (log.contains("Duration:")) {
+            QString data = log.section("Duration:", 1, 1).section(',', 0, 0).simplified();
+            QStringList numbers = data.split(':');
+            *duration = (int) (numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble());
+        }
+    }
+    else if (log.contains("time=")) {
+        QString time = log.section("time=", 1, 1).simplified().section(' ', 0, 0);
+        if (time.contains(':')) {
+            QStringList numbers = time.split(':');
+            progress = numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble();
+        }
+        else progress = (int) time.toDouble();
+        setProxyStatus(path, CREATINGPROXY, (int) (100.0 * progress / (*duration)));
     }
-    m_abortProxy.removeAll(destPath);
-    m_processingProxy.removeAll(destPath);
 }
 
 void ProjectList::updateProxyConfig()
@@ -2448,8 +2567,6 @@ void ProjectList::updateProxyConfig()
     }
     if (command->childCount() > 0) m_doc->commandStack()->push(command);
     else delete command;
-    //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
 }
 
 void ProjectList::slotProxyCurrentItem(bool doProxy)
@@ -2475,10 +2592,15 @@ void ProjectList::slotProxyCurrentItem(bool doProxy)
                 if (!list.contains(sub)) list.append(sub);
             }
         }
-        if (listItem->type() == PROJECTCLIPTYPE) {
+        else if (listItem->type() == PROJECTSUBCLIPTYPE) {
+            QTreeWidgetItem *sub = listItem->parent();
+            if (!list.contains(sub)) list.append(sub);
+        }
+        else if (listItem->type() == PROJECTCLIPTYPE) {
             ProjectItem *item = static_cast <ProjectItem*>(listItem);
             CLIPTYPE t = item->clipType();
             if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
+                if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy())) continue;
                 oldProps = item->referencedClip()->properties();
                 if (doProxy) {
                     newProps.clear();
@@ -2497,8 +2619,6 @@ void ProjectList::slotProxyCurrentItem(bool doProxy)
         m_doc->commandStack()->push(command);
     }
     else delete command;
-    //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
-    if (!m_infoQueue.isEmpty()) QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
 }
 
 
@@ -2528,27 +2648,27 @@ void ProjectList::slotDeleteProxy(const QString proxyPath)
     QFile::remove(proxyPath);
 }
 
-void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status)
+void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status, int progress)
 {
-    if (proxyPath.isEmpty()) return;
+    if (proxyPath.isEmpty() || m_abortAllProxies) return;
     QTreeWidgetItemIterator it(m_listView);
     ProjectItem *item;
     while (*it) {
         if ((*it)->type() == PROJECTCLIPTYPE) {
             item = static_cast <ProjectItem *>(*it);
             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
-                setProxyStatus(item, status);
+                setProxyStatus(item, status, progress);
             }
         }
         ++it;
     }
 }
 
-void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status)
+void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status, int progress)
 {
     if (item == NULL) return;
     monitorItemEditing(false);
-    item->setProxyStatus(status);
+    item->setProxyStatus(status, progress);
     monitorItemEditing(true);
 }