]> git.sesse.net Git - kdenlive/blobdiff - src/kthumb.cpp
Fix some more threading crashes, almost there :)
[kdenlive] / src / kthumb.cpp
index 413f7bf968e89356df35102ecc83cf9f410dbf95..6eb212a7d358eac233f2e889edbb4a1037596601 100644 (file)
@@ -38,7 +38,7 @@
 #include <QImage>
 #include <QApplication>
 #include <QtConcurrentRun>
-
+#include <QVarLengthArray>
 
 KThumb::KThumb(ClipManager *clipManager, KUrl url, const QString &id, const QString &hash, QObject * parent, const char */*name*/) :
     QObject(parent),
@@ -46,6 +46,7 @@ KThumb::KThumb(ClipManager *clipManager, KUrl url, const QString &id, const QStr
     m_url(url),
     m_thumbFile(),
     m_dar(1),
+    m_ratio(1),
     m_producer(NULL),
     m_clipManager(clipManager),
     m_id(id),
@@ -56,28 +57,41 @@ KThumb::KThumb(ClipManager *clipManager, KUrl url, const QString &id, const QStr
 
 KThumb::~KThumb()
 {
+    m_listMutex.lock();
     m_requestedThumbs.clear();
+    m_listMutex.unlock();
+    m_intraFramesQueue.clear();
     if (m_audioThumbProducer.isRunning()) {
         m_stopAudioThumbs = true;
         m_audioThumbProducer.waitForFinished();
         slotAudioThumbOver();
     }
     m_future.waitForFinished();
+    m_intra.waitForFinished();
 }
 
 void KThumb::setProducer(Mlt::Producer *producer)
 {
+    m_listMutex.lock();
     m_requestedThumbs.clear();
+    m_listMutex.unlock();
+    m_intraFramesQueue.clear();
     m_future.waitForFinished();
+    m_intra.waitForFinished();
+    m_mutex.lock();
     m_producer = producer;
     // FIXME: the profile() call leaks an object, but trying to free
     // it leads to a double-free in Profile::~Profile()
-    m_dar = producer->profile()->dar();
+    if (producer) {
+        m_dar = producer->profile()->dar();
+        m_ratio = (double) producer->profile()->width() / producer->profile()->height();
+    }
+    m_mutex.unlock();
 }
 
 void KThumb::clearProducer()
 {
-    m_producer = NULL;
+    setProducer(NULL);
 }
 
 bool KThumb::hasProducer() const
@@ -93,8 +107,6 @@ void KThumb::updateThumbUrl(const QString &hash)
 void KThumb::updateClipUrl(KUrl url, const QString &hash)
 {
     m_url = url;
-    if (m_producer)
-        m_producer->set("resource", url.path().toUtf8().constData());
     m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
 }
 
@@ -108,20 +120,28 @@ QPixmap KThumb::getImage(KUrl url, int width, int height)
 void KThumb::extractImage(int frame, int frame2)
 {
     if (!KdenliveSettings::videothumbnails() || m_producer == NULL) return;
+    m_listMutex.lock();
     if (frame != -1 && !m_requestedThumbs.contains(frame)) m_requestedThumbs.append(frame);
     if (frame2 != -1 && !m_requestedThumbs.contains(frame2)) m_requestedThumbs.append(frame2);
-    if (!m_future.isRunning()) m_future = QtConcurrent::run(this, &KThumb::doGetThumbs);
+    qSort(m_requestedThumbs);
+    m_listMutex.unlock();
+    if (!m_future.isRunning()) {
+        m_future = QtConcurrent::run(this, &KThumb::doGetThumbs);
+    }
 }
 
 void KThumb::doGetThumbs()
 {
     const int theight = KdenliveSettings::trackheight();
-    const int twidth = FRAME_SIZE;//(int)(theight * m_dar + 0.5);
+    const int swidth = (int)(theight * m_ratio + 0.5);
+    const int dwidth = (int)(theight * m_dar + 0.5);
 
     while (!m_requestedThumbs.isEmpty()) {
+        m_listMutex.lock();
         int frame = m_requestedThumbs.takeFirst();
+        m_listMutex.unlock();
         if (frame != -1) {
-            QImage img = getFrame(m_producer, frame, twidth, theight);
+            QImage img = getProducerFrame(frame, swidth, dwidth, theight);
             emit thumbReady(frame, img);
         }
     }
@@ -129,7 +149,13 @@ void KThumb::doGetThumbs()
 
 QPixmap KThumb::extractImage(int frame, int width, int height)
 {
-    return QPixmap::fromImage(getFrame(m_producer, frame, width, height));
+    if (m_producer == NULL) {
+        QPixmap p(width, height);
+        p.fill(Qt::black);
+        return p;
+    }
+    QImage img = getProducerFrame(frame, (int) (height * m_ratio + 0.5), width, height);
+    return QPixmap::fromImage(img);
 }
 
 //static
@@ -142,57 +168,120 @@ QPixmap KThumb::getImage(KUrl url, int frame, int width, int height)
     //"<mlt><playlist><producer resource=\"" + url.path() + "\" /></playlist></mlt>");
     //Mlt::Producer producer(profile, "xml-string", tmp);
     Mlt::Producer *producer = new Mlt::Producer(profile, url.path().toUtf8().constData());
-
-    pix = QPixmap::fromImage(getFrame(producer, frame, width, height));
+    double swidth = (double) profile.width() / profile.height();
+    pix = QPixmap::fromImage(getFrame(producer, frame, (int) (height * swidth + 0.5), width, height));
     delete producer;
     return pix;
 }
 
 
-//static
-QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int width, int height)
+QImage KThumb::getProducerFrame(int framepos, int frameWidth, int displayWidth, int height)
 {
-    QImage p(width, height, QImage::Format_ARGB32_Premultiplied);
-    if (producer == NULL) {
-        p.fill(Qt::red);
+    if (m_producer == NULL || !m_producer->is_valid()) {
+        QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
+        p.fill(QColor(Qt::red).rgb());
         return p;
     }
+    if (m_producer->is_blank()) {
+        QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
+        p.fill(QColor(Qt::black).rgb());
+        return p;
+    }
+    m_mutex.lock();
+    m_producer->seek(framepos);
+    Mlt::Frame *frame = m_producer->get_frame();
+    QImage p = getFrame(frame, frameWidth, displayWidth, height);
+    delete frame;
+    m_mutex.unlock();
+    return p;
+}
 
+//static
+QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int frameWidth, int displayWidth, int height)
+{
+    if (producer == NULL || !producer->is_valid()) {
+        QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
+        p.fill(QColor(Qt::red).rgb());
+        return p;
+    }
     if (producer->is_blank()) {
-        p.fill(Qt::black);
+        QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
+        p.fill(QColor(Qt::black).rgb());
         return p;
     }
 
     producer->seek(framepos);
     Mlt::Frame *frame = producer->get_frame();
-    if (!frame) {
-        kDebug() << "///// BROKEN FRAME";
-        p.fill(Qt::red);
+    QImage p = getFrame(frame, frameWidth, displayWidth, height);
+    delete frame;
+    return p;
+}
+
+
+//static
+QImage KThumb::getFrame(Mlt::Frame *frame, int frameWidth, int displayWidth, int height)
+{
+    QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
+    if (frame == NULL || !frame->is_valid()) {
+        p.fill(QColor(Qt::red).rgb());
         return p;
     }
 
-    /*Mlt::Producer parentProd(producer->parent());
-    Mlt::Service service(parentProd.get_service());
-    mlt_service_lock(service.get_service());*/
-    int ow = width;
+    int ow = frameWidth;
     int oh = height;
     mlt_image_format format = mlt_image_rgb24a;
-    uint8_t *data = frame->get_image(format, ow, oh, 0);
-    QImage image((uchar *)data, ow, oh, QImage::Format_ARGB32_Premultiplied);
-    //mlt_service_unlock(service.get_service());
-
+    
+    const uchar* imagedata = frame->get_image(format, ow, oh);
+    QImage image(imagedata, ow, oh, QImage::Format_ARGB32_Premultiplied);
+    
     if (!image.isNull()) {
-        if (ow > (2 * width)) {
+        if (ow > (2 * displayWidth)) {
             // there was a scaling problem, do it manually
-            QImage scaled = image.scaled(width, height);
-            p = scaled.rgbSwapped();
-        } else p = image.rgbSwapped();
+            image = image.scaled(displayWidth, height).rgbSwapped();
+        } else {
+            image = image.scaled(displayWidth, height, Qt::IgnoreAspectRatio).rgbSwapped();
+        }
+        p.fill(QColor(Qt::black).rgb());
+        QPainter painter(&p);
+        painter.drawImage(p.rect(), image);
+        painter.end();
     } else
-        p.fill(Qt::red);
-
-    delete frame;
+        p.fill(QColor(Qt::red).rgb());
     return p;
 }
+
+//static
+uint KThumb::imageVariance(QImage image )
+{
+    uint delta = 0;
+    uint avg = 0;
+    uint bytes = image.numBytes();
+    uint STEPS = bytes/2;
+    QVarLengthArray<uchar> pivot(STEPS);
+    const uchar *bits=image.bits();
+    // First pass: get pivots and taking average
+    for( uint i=0; i<STEPS ; i++ ){
+        pivot[i] = bits[2 * i];
+#if QT_VERSION >= 0x040700
+        avg+=pivot.at(i);
+#else
+        avg+=pivot[i];
+#endif
+    }
+    avg=avg/STEPS;
+    // Second Step: calculate delta (average?)
+    for (uint i=0; i<STEPS; i++)
+    {
+#if QT_VERSION >= 0x040700
+        int curdelta=abs(int(avg - pivot.at(i)));
+#else
+        int curdelta=abs(int(avg - pivot[i]));
+#endif
+        delta+=curdelta;
+    }
+    return delta/STEPS;
+}
+
 /*
 void KThumb::getImage(KUrl url, int frame, int width, int height)
 {
@@ -291,14 +380,14 @@ void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int a
         return;
     }
 
-    QMap <int, QMap <int, QByteArray> > storeIn;
+    audioByteArray storeIn;
     //FIXME: Hardcoded!!!
     m_frequency = 48000;
     m_channels = channel;
 
     QFile f(m_thumbFile);
     if (f.open(QIODevice::ReadOnly)) {
-        QByteArray channelarray = f.readAll();
+        const QByteArray channelarray = f.readAll();
         f.close();
         if (channelarray.size() != arrayWidth*(frame + frameLength)*m_channels) {
             kDebug() << "--- BROKEN THUMB FOR: " << m_url.fileName() << " ---------------------- " << endl;
@@ -313,15 +402,16 @@ void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int a
         int h2 = (int) frame * h1;
         int h3;
         for (int z = (int) frame; z < (int)(frame + frameLength); z++) {
-            h2 += h1;
             h3 = 0;
             for (int c = 0; c < m_channels; c++) {
-                h3 += arrayWidth;
                 QByteArray m_array(arrayWidth, '\x00');
-                for (int i = 0; i < arrayWidth; i++)
-                    m_array[i] = channelarray[h2 + h3 + i];
+                for (int i = 0; i < arrayWidth; i++) {
+                    m_array[i] = channelarray.at(h2 + h3 + i);
+                }
+                h3 += arrayWidth;
                 storeIn[z][c] = m_array;
             }
+            h2 += h1;
         }
         emit audioThumbReady(storeIn);
         slotAudioThumbOver();
@@ -340,35 +430,39 @@ void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int a
 
 void KThumb::slotCreateAudioThumbs()
 {
+    Mlt::Profile prof((char*) KdenliveSettings::current_profile().toUtf8().data());
+    Mlt::Producer producer(prof, m_url.path().toUtf8().data());
+    if (!producer.is_valid()) {
+        kDebug() << "++++++++  INVALID CLIP: " << m_url.path();
+        return;
+    }
     if (!m_audioThumbFile.open(QIODevice::WriteOnly)) {
         kDebug() << "++++++++  ERROR WRITING TO FILE: " << m_audioThumbFile.fileName();
         kDebug() << "++++++++  DISABLING AUDIO THUMBS";
         KdenliveSettings::setAudiothumbnails(false);
         return;
     }
-    Mlt::Profile prof((char*) KdenliveSettings::current_profile().toUtf8().data());
-    Mlt::Producer m_producer(prof, m_url.path().toUtf8().data());
 
     if (KdenliveSettings::normaliseaudiothumbs()) {
         Mlt::Filter m_convert(prof, "volume");
         m_convert.set("gain", "normalise");
-        m_producer.attach(m_convert);
+        producer.attach(m_convert);
     }
 
     int last_val = 0;
     int val = 0;
-    kDebug() << "for " << m_frame << " " << m_frameLength << " " << m_producer.is_valid();
-    for (int z = (int) m_frame; z < (int)(m_frame + m_frameLength) && m_producer.is_valid(); z++) {
+    //kDebug() << "for " << m_frame << " " << m_frameLength << " " << m_producer.is_valid();
+    for (int z = (int) m_frame; z < (int)(m_frame + m_frameLength) && producer.is_valid(); z++) {
         if (m_stopAudioThumbs) break;
         val = (int)((z - m_frame) / (m_frame + m_frameLength) * 100.0);
         if (last_val != val && val > 1) {
             m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), val);
             last_val = val;
         }
-        m_producer.seek(z);
-        Mlt::Frame *mlt_frame = m_producer.get_frame();
+        producer.seek(z);
+        Mlt::Frame *mlt_frame = producer.get_frame();
         if (mlt_frame && mlt_frame->is_valid()) {
-            double m_framesPerSecond = mlt_producer_get_fps(m_producer.get_producer());
+            double m_framesPerSecond = mlt_producer_get_fps(producer.get_producer());
             int m_samples = mlt_sample_calculator(m_framesPerSecond, m_frequency, mlt_frame_get_position(mlt_frame->get_frame()));
             mlt_audio_format m_audioFormat = mlt_audio_pcm;
             qint16* m_pcm = static_cast<qint16*>(mlt_frame->get_audio(m_audioFormat, m_frequency, m_channels, m_samples));
@@ -406,6 +500,46 @@ void KThumb::askForAudioThumbs(const QString &id)
     m_clipManager->askForAudioThumb(id);
 }
 
+#if KDE_IS_VERSION(4,5,0)
+void KThumb::queryIntraThumbs(QList <int> missingFrames)
+{
+    foreach (int i, missingFrames) {
+        if (!m_intraFramesQueue.contains(i)) m_intraFramesQueue.append(i);
+    }
+    qSort(m_intraFramesQueue);
+    if (!m_intra.isRunning()) {
+        m_intra = QtConcurrent::run(this, &KThumb::slotGetIntraThumbs);
+    }
+}
+
+void KThumb::slotGetIntraThumbs()
+{
+    const int theight = KdenliveSettings::trackheight();
+    const int frameWidth = (int)(theight * m_ratio + 0.5);
+    const int displayWidth = (int)(theight * m_dar + 0.5);
+    QString path = m_url.path() + "_";
+    bool addedThumbs = false;
+
+    while (!m_intraFramesQueue.isEmpty()) {
+        int pos = m_intraFramesQueue.takeFirst();
+        if (!m_clipManager->pixmapCache->contains(path + QString::number(pos))) {
+            if (m_clipManager->pixmapCache->insertImage(path + QString::number(pos), getProducerFrame(pos, frameWidth, displayWidth, theight))) {
+                addedThumbs = true;
+            }
+            else kDebug()<<"// INSERT FAILD FOR: "<<pos;
+        }
+        m_intraFramesQueue.removeAll(pos);
+    }
+    if (addedThumbs) emit thumbsCached();
+}
+
+QImage KThumb::findCachedThumb(const QString path)
+{
+    QImage img;
+    m_clipManager->pixmapCache->findImage(path, &img);
+    return img;
+}
+#endif
 
 #include "kthumb.moc"