]> git.sesse.net Git - kdenlive/blobdiff - src/renderer.cpp
- Fix split audio with locked audio tracks
[kdenlive] / src / renderer.cpp
index affbff833fb4770f008cbe7712f7dae0cbfcb030..2a78c8e6cc88bb8f18ebbb696c42125da2d68503 100644 (file)
 
 #include <QTimer>
 #include <QDir>
+#include <QString>
 #include <QApplication>
 
-#include <stdlib.h>
+#include <cstdlib>
+#include <cstdarg>
+
+
+
+static void kdenlive_callback(void* /*ptr*/, int level, const char* fmt, va_list vl)
+{
+    if (level > MLT_LOG_ERROR) return;
+    QString error;
+    QApplication::postEvent(qApp->activeWindow() , new MltErrorEvent(error.vsprintf(fmt, vl).simplified()));
+    va_end(vl);
+}
+
 
 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr)
 {
     // detect if the producer has finished playing. Is there a better way to do it?
     if (self->m_isBlocked) return;
-    if (mlt_properties_get_double(MLT_FRAME_PROPERTIES(frame_ptr), "_speed") == 0.0) {
+    Mlt::Frame frame(frame_ptr);
+#ifdef Q_WS_MAC
+    self->showFrame(frame);
+#endif
+
+    self->emitFrameNumber(mlt_frame_get_position(frame_ptr));
+    if (frame.get_double("_speed") == 0.0) {
+        self->emitConsumerStopped();
+    } else if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
+        self->pause();
         self->emitConsumerStopped();
-    } else {
-        self->emitFrameNumber(mlt_frame_get_position(frame_ptr));
     }
 }
 
-Render::Render(const QString & rendererName, int winid, int /* extid */, QWidget *parent) :
+
+Render::Render(const QString & rendererName, int winid, int /* extid */, QString profile, QWidget *parent) :
         QObject(parent),
         m_isBlocked(0),
         m_name(rendererName),
         m_mltConsumer(NULL),
         m_mltProducer(NULL),
+        m_mltProfile(NULL),
         m_framePosition(0),
         m_isZoneMode(false),
         m_isLoopMode(false),
         m_isSplitView(false),
         m_blackClip(NULL),
         m_winid(winid)
+#ifdef Q_WS_MAC
+        , m_glWidget(0)
+#endif
 {
-    kDebug() << "//////////  USING PROFILE: " << (char*)KdenliveSettings::current_profile().toUtf8().data();
-    m_refreshTimer = new QTimer(this);
-    connect(m_refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
-
     /*if (rendererName == "project") m_monitorId = 10000;
     else m_monitorId = 10001;*/
-    m_osdTimer = new QTimer(this);
-    connect(m_osdTimer, SIGNAL(timeout()), this, SLOT(slotOsdTimeout()));
-
-    buildConsumer();
+    /*m_osdTimer = new QTimer(this);
+    connect(m_osdTimer, SIGNAL(timeout()), this, SLOT(slotOsdTimeout()));*/
+    if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
+    buildConsumer(profile);
 
     m_mltProducer = m_blackClip->cut(0, 50);
     m_mltConsumer->connect(*m_mltProducer);
@@ -91,24 +112,63 @@ Render::~Render()
 
 void Render::closeMlt()
 {
-    delete m_osdTimer;
-    delete m_refreshTimer;
+    //delete m_osdTimer;
+    if (m_mltProducer) {
+        Mlt::Service service(m_mltProducer->parent().get_service());
+        mlt_service_lock(service.get_service());
+
+        if (service.type() == tractor_type) {
+            Mlt::Tractor tractor(service);
+            Mlt::Field *field = tractor.field();
+            mlt_service nextservice = mlt_service_get_producer(service.get_service());
+            mlt_service nextservicetodisconnect;
+            mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
+            QString mlt_type = mlt_properties_get(properties, "mlt_type");
+            QString resource = mlt_properties_get(properties, "mlt_service");
+            // Delete all transitions
+            while (mlt_type == "transition") {
+                nextservicetodisconnect = nextservice;
+                nextservice = mlt_service_producer(nextservice);
+                mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
+                nextservice = mlt_service_producer(nextservice);
+                if (nextservice == NULL) break;
+                properties = MLT_SERVICE_PROPERTIES(nextservice);
+                mlt_type = mlt_properties_get(properties, "mlt_type");
+                resource = mlt_properties_get(properties, "mlt_service");
+            }
+
+            for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
+                Mlt::Producer trackProducer(tractor.track(trackNb));
+                Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+                if (trackPlaylist.type() == playlist_type) trackPlaylist.clear();
+            }
+        }
+        mlt_service_unlock(service.get_service());
+    }
+
+    kDebug() << "// // // CLOSE RENDERER " << m_name;
     delete m_mltConsumer;
     delete m_mltProducer;
     delete m_blackClip;
     //delete m_osdInfo;
 }
 
+void Render::slotSwitchFullscreen()
+{
+    if (m_mltConsumer) m_mltConsumer->set("full_screen", 1);
+}
 
-void Render::buildConsumer()
+void Render::buildConsumer(const QString profileName)
 {
     char *tmp;
-    m_activeProfile = KdenliveSettings::current_profile();
+    m_activeProfile = profileName;
     tmp = decodedString(m_activeProfile);
     setenv("MLT_PROFILE", tmp, 1);
     delete m_blackClip;
     m_blackClip = NULL;
 
+    //TODO: uncomment following line when everything is clean
+    //if (m_mltProfile) delete m_mltProfile;
     m_mltProfile = new Mlt::Profile(tmp);
     delete[] tmp;
 
@@ -123,7 +183,14 @@ void Render::buildConsumer()
     }
     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
 
+    //m_mltConsumer->set("fullscreen", 1);
+#ifdef Q_WS_MAC
+    m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_audio");
+    m_mltConsumer->set("preview_off", 1);
+    m_mltConsumer->set("preview_format", mlt_image_rgb24a);
+#else
     m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview");
+#endif
     m_mltConsumer->set("resize", 1);
     m_mltConsumer->set("window_id", m_winid);
     m_mltConsumer->set("terminate_on_pause", 1);
@@ -134,6 +201,7 @@ void Render::buildConsumer()
     // FIXME: the event object returned by the listen gets leaked...
     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
     m_mltConsumer->set("rescale", "nearest");
+    mlt_log_set_callback(kdenlive_callback);
 
     QString audioDevice = KdenliveSettings::audiodevicename();
     if (!audioDevice.isEmpty()) {
@@ -149,8 +217,13 @@ void Render::buildConsumer()
     }
 
     QString audioDriver = KdenliveSettings::audiodrivername();
+
+    /*
+    // Disabled because the "auto" detected driver was sometimes wrong
     if (audioDriver.isEmpty())
         audioDriver = KdenliveSettings::autoaudiodrivername();
+    */
+
     if (!audioDriver.isEmpty()) {
         tmp = decodedString(audioDriver);
         m_mltConsumer->set("audio_driver", tmp);
@@ -164,39 +237,70 @@ void Render::buildConsumer()
 
     m_blackClip = new Mlt::Producer(*m_mltProfile , "colour", "black");
     m_blackClip->set("id", "black");
+    m_blackClip->set("mlt_type", "producer");
+
+}
 
+Mlt::Producer *Render::invalidProducer(const QString &id)
+{
+    Mlt::Producer *clip = new Mlt::Producer(*m_mltProfile , "colour", "red");
+    char *tmp = decodedString(id);
+    clip->set("id", tmp);
+    delete[] tmp;
+    clip->set("mlt_type", "producer");
+    return clip;
 }
 
-int Render::resetProfile()
+int Render::resetProfile(const QString profileName)
 {
-    if (!m_mltConsumer) return 0;
-    if (m_activeProfile == KdenliveSettings::current_profile()) {
-        kDebug() << "reset to same profile, nothing to do";
-        return 1;
+    if (m_mltConsumer) {
+        QString videoDriver = KdenliveSettings::videodrivername();
+        QString currentDriver = m_mltConsumer->get("video_driver");
+        if (getenv("SDL_VIDEO_YUV_HWACCEL") != NULL && currentDriver == "x11") currentDriver = "x11_noaccel";
+        if (m_activeProfile == profileName && currentDriver == videoDriver) {
+            kDebug() << "reset to same profile, nothing to do";
+            return 1;
+        }
+
+        if (m_isSplitView) slotSplitView(false);
+        if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
+        m_mltConsumer->purge();
+        delete m_mltConsumer;
+        m_mltConsumer = NULL;
     }
-    kDebug() << "// RESETTING PROFILE FROM: " << m_activeProfile << " TO: " << KdenliveSettings::current_profile();
-    if (m_isSplitView) slotSplitView(false);
-    if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
-    m_mltConsumer->purge();
-    delete m_mltConsumer;
-    m_mltConsumer = NULL;
     QString scene = sceneList();
     int pos = 0;
+    double current_fps = m_mltProfile->fps();
+    delete m_blackClip;
+    m_blackClip = NULL;
+
     if (m_mltProducer) {
         pos = m_mltProducer->position();
+
+        Mlt::Service service(m_mltProducer->get_service());
+        if (service.type() == tractor_type) {
+            Mlt::Tractor tractor(service);
+            for (int trackNb = tractor.count() -1; trackNb >= 0; --trackNb) {
+                Mlt::Producer trackProducer(tractor.track(trackNb));
+                Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+                trackPlaylist.clear();
+            }
+        }
+
         delete m_mltProducer;
     }
     m_mltProducer = NULL;
 
-    //WARNING: Trying to delete the profile will crash when trying to display a clip afterwards...
-    /*if (m_mltProfile) delete m_mltProfile;
-    m_mltProfile = NULL;*/
-
-    buildConsumer();
-
+    buildConsumer(profileName);
+    double new_fps = m_mltProfile->fps();
+    if (current_fps != new_fps) {
+        // fps changed, we must update the scenelist positions
+        scene = updateSceneListFps(current_fps, new_fps, scene);
+    }
     //kDebug() << "//RESET WITHSCENE: " << scene;
     setSceneList(scene, pos);
-
+    // producers have changed (different profile), so reset them...
+    emit refreshDocumentProducers();
     /*char *tmp = decodedString(scene);
     Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "xml-string", tmp);
     delete[] tmp;
@@ -219,12 +323,11 @@ int Render::resetProfile()
     return 1;
 }
 
-/** Wraps the VEML command of the same name; Seeks the renderer clip to the given time. */
 void Render::seek(GenTime time)
 {
     if (!m_mltProducer)
         return;
-    m_isBlocked = 0;
+    m_isBlocked = false;
     m_mltProducer->seek((int)(time.frames(m_fps)));
     refresh();
 }
@@ -259,7 +362,7 @@ char *Render::decodedString(QString str)
 */
 int Render::renderWidth() const
 {
-    return (int)(m_mltProfile->height() * m_mltProfile->dar());
+    return (int)(m_mltProfile->height() * m_mltProfile->dar() + 0.5);
 }
 
 int Render::renderHeight() const
@@ -267,14 +370,15 @@ int Render::renderHeight() const
     return m_mltProfile->height();
 }
 
-QPixmap Render::extractFrame(int frame_position, int width, int height)
+QImage Render::extractFrame(int frame_position, int width, int height)
 {
     if (width == -1) {
         width = renderWidth();
         height = renderHeight();
     } else if (width % 2 == 1) width++;
-    QPixmap pix(width, height);
+
     if (!m_mltProducer) {
+        QImage pix(width, height, QImage::Format_RGB32);
         pix.fill(Qt::black);
         return pix;
     }
@@ -434,8 +538,7 @@ void Render::slotSplitView(bool doit)
     if (service.type() != tractor_type || tractor.count() < 2) return;
     Mlt::Field *field = tractor.field();
     if (doit) {
-        int screen = 0;
-        for (int i = 1; i < tractor.count() && screen < 4; i++) {
+        for (int i = 1, screen = 0; i < tractor.count() && screen < 4; i++) {
             Mlt::Producer trackProducer(tractor.track(i));
             kDebug() << "// TRACK: " << i << ", HIDE: " << trackProducer.get("hide");
             if (QString(trackProducer.get("hide")).toInt() != 1) {
@@ -492,18 +595,28 @@ void Render::slotSplitView(bool doit)
     }
 }
 
-void Render::getFileProperties(const QDomElement &xml, const QString &clipId, bool replaceProducer)
+void Render::getFileProperties(const QDomElement xml, const QString &clipId, int imageHeight, bool replaceProducer)
 {
     KUrl url = KUrl(xml.attribute("resource", QString()));
     Mlt::Producer *producer = NULL;
-    if (xml.attribute("type").toInt() == TEXT && !QFile::exists(url.path())) {
+    //kDebug() << "PROFILE WIDT: "<< xml.attribute("mlt_service") << ": "<< m_mltProfile->width() << "\n...................\n\n";
+    /*if (xml.attribute("type").toInt() == TEXT && !QFile::exists(url.path())) {
         emit replyGetFileProperties(clipId, producer, QMap < QString, QString >(), QMap < QString, QString >(), replaceProducer);
         return;
-    }
+    }*/
     if (xml.attribute("type").toInt() == COLOR) {
         char *tmp = decodedString("colour:" + xml.attribute("colour"));
         producer = new Mlt::Producer(*m_mltProfile, 0, tmp);
         delete[] tmp;
+    } else if (xml.attribute("type").toInt() == TEXT) {
+        char *tmp = decodedString("kdenlivetitle:" + xml.attribute("resource"));
+        producer = new Mlt::Producer(*m_mltProfile, 0, tmp);
+        delete[] tmp;
+        if (producer && xml.hasAttribute("xmldata")) {
+            tmp = decodedString(xml.attribute("xmldata"));
+            producer->set("xmldata", tmp);
+            delete[] tmp;
+        }
     } else if (url.isEmpty()) {
         QDomDocument doc;
         QDomElement mlt = doc.createElement("mlt");
@@ -531,6 +644,17 @@ void Render::getFileProperties(const QDomElement &xml, const QString &clipId, bo
         double aspect = xml.attribute("force_aspect_ratio").toDouble();
         if (aspect > 0) producer->set("force_aspect_ratio", aspect);
     }
+
+    if (xml.hasAttribute("force_fps")) {
+        double fps = xml.attribute("force_fps").toDouble();
+        if (fps > 0) producer->set("force_fps", fps);
+    }
+
+    if (xml.hasAttribute("force_progressive")) {
+        bool ok;
+        int progressive = xml.attribute("force_progressive").toInt(&ok);
+        if (ok) producer->set("force_progressive", progressive);
+    }
     if (xml.hasAttribute("threads")) {
         int threads = xml.attribute("threads").toInt();
         if (threads != 1) producer->set("threads", threads);
@@ -550,8 +674,19 @@ void Render::getFileProperties(const QDomElement &xml, const QString &clipId, bo
     producer->set("id", tmp);
     delete[] tmp;
 
-    int height = 50;
-    int width = (int)(height  * m_mltProfile->dar());
+    if (xml.hasAttribute("templatetext")) {
+        char *tmp = decodedString(xml.attribute("templatetext"));
+        producer->set("templatetext", tmp);
+        delete[] tmp;
+    }
+
+    if (!replaceProducer && xml.hasAttribute("file_hash")) {
+        // Clip  already has all properties
+        emit replyGetFileProperties(clipId, producer, QMap < QString, QString >(), QMap < QString, QString >(), replaceProducer);
+        return;
+    }
+
+    int width = (int)(imageHeight * m_mltProfile->dar() + 0.5);
     QMap < QString, QString > filePropertyMap;
     QMap < QString, QString > metadataPropertyMap;
 
@@ -604,34 +739,27 @@ void Render::getFileProperties(const QDomElement &xml, const QString &clipId, bo
             else
                 filePropertyMap["type"] = "video";
 
-            mlt_image_format format = mlt_image_yuv422;
-            int frame_width = 0;
-            int frame_height = 0;
-            //frame->set("rescale.interp", "hyper");
-            frame->set("normalised_height", height);
-            frame->set("normalised_width", width);
-            QPixmap pix(width, height);
-
+            mlt_image_format format = mlt_image_rgb24a;
+            int frame_width = width;
+            int frame_height = imageHeight;
             uint8_t *data = frame->get_image(format, frame_width, frame_height, 0);
-            uint8_t *new_image = (uint8_t *)mlt_pool_alloc(frame_width * (frame_height + 1) * 4);
-            mlt_convert_yuv422_to_rgb24a((uint8_t *)data, new_image, frame_width * frame_height);
-            QImage image((uchar *)new_image, frame_width, frame_height, QImage::Format_ARGB32);
+            QImage image((uchar *)data, frame_width, frame_height, QImage::Format_ARGB32);
+            QPixmap pix(frame_width, frame_height);
 
             if (!image.isNull()) {
                 pix = QPixmap::fromImage(image.rgbSwapped());
             } else
                 pix.fill(Qt::black);
 
-            mlt_pool_release(new_image);
             emit replyGetImage(clipId, pix);
 
         } else if (frame->get_int("test_audio") == 0) {
-            QPixmap pixmap = KIcon("audio-x-generic").pixmap(QSize(width, height));
+            QPixmap pixmap = KIcon("audio-x-generic").pixmap(QSize(width, imageHeight));
             emit replyGetImage(clipId, pixmap);
             filePropertyMap["type"] = "audio";
         }
     }
-
+    delete frame;
     // Retrieve audio / video codec name
 
     // If there is a
@@ -708,17 +836,16 @@ void Render::getFileProperties(const QDomElement &xml, const QString &clipId, bo
         if (name.endsWith("markup") && !value.isEmpty())
             metadataPropertyMap[ name.section('.', 0, -2)] = value;
     }
-
-    emit replyGetFileProperties(clipId, producer, filePropertyMap, metadataPropertyMap, replaceProducer);
+    producer->seek(0);
     kDebug() << "REquested fuile info for: " << url.path();
-    delete frame;
+    emit replyGetFileProperties(clipId, producer, filePropertyMap, metadataPropertyMap, replaceProducer);
     // FIXME: should delete this to avoid a leak...
     //delete producer;
 }
 
 
-/** Create the producer from the MLT XML QDomDocument */
 #if 0
+/** Create the producer from the MLT XML QDomDocument */
 void Render::initSceneList()
 {
     kDebug() << "--------  INIT SCENE LIST ------_";
@@ -755,16 +882,13 @@ void Render::initSceneList()
 }
 #endif
 
-
-
-/** Create the producer from the MLT XML QDomDocument */
-void Render::setProducer(Mlt::Producer *producer, int position)
+int Render::setProducer(Mlt::Producer *producer, int position)
 {
-    if (m_winid == -1) return;
+    if (m_winid == -1) return -1;
 
     if (m_mltConsumer) {
         m_mltConsumer->stop();
-    } else return;
+    } else return -1;
 
     m_mltConsumer->purge();
 
@@ -782,50 +906,84 @@ void Render::setProducer(Mlt::Producer *producer, int position)
     m_mltProducer->set("skip_loop_filter", "all");
         m_mltProducer->set("skip_frame", "bidir");
     }*/
-    if (!m_mltProducer || !m_mltProducer->is_valid()) kDebug() << " WARNING - - - - -INVALID PLAYLIST: ";
+    if (!m_mltProducer || !m_mltProducer->is_valid()) {
+        kDebug() << " WARNING - - - - -INVALID PLAYLIST: ";
+        return -1;
+    }
 
     m_fps = m_mltProducer->get_fps();
-    connectPlaylist();
+    int error = connectPlaylist();
+
     if (position != -1) {
         m_mltProducer->seek(position);
         emit rendererPosition(position);
     }
     m_isBlocked = false;
+    return error;
 }
 
-
-
-/** Create the producer from the MLT XML QDomDocument */
-void Render::setSceneList(QDomDocument list, int position)
+int Render::setSceneList(QDomDocument list, int position)
 {
-    setSceneList(list.toString(), position);
+    return setSceneList(list.toString(), position);
 }
 
-/** Create the producer from the MLT XML QDomDocument */
-void Render::setSceneList(QString playlist, int position)
+int Render::setSceneList(QString playlist, int position)
 {
-    if (m_winid == -1) return;
+    if (m_winid == -1) return -1;
     m_isBlocked = true;
-    qDeleteAll(m_slowmotionProducers.values());
-    m_slowmotionProducers.clear();
+    int error = 0;
 
-    //kWarning() << "//////  RENDER, SET SCENE LIST: " << playlist;
+    kDebug() << "//////  RENDER, SET SCENE LIST: " << playlist;
 
-    if (m_mltConsumer == NULL) {
+    if (m_mltConsumer) {
+        if (!m_mltConsumer->is_stopped()) {
+            m_mltConsumer->stop();
+        }
+        m_mltConsumer->set("refresh", 0);
+    } else {
         kWarning() << "///////  ERROR, TRYING TO USE NULL MLT CONSUMER";
-        m_isBlocked = false;
-        return;
-    }
-
-    if (!m_mltConsumer->is_stopped()) {
-        m_mltConsumer->stop();
-        //m_mltConsumer->set("refresh", 0);
+        error = -1;
     }
 
     if (m_mltProducer) {
         m_mltProducer->set_speed(0);
         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
 
+
+        Mlt::Service service(m_mltProducer->parent().get_service());
+        mlt_service_lock(service.get_service());
+
+        if (service.type() == tractor_type) {
+            Mlt::Tractor tractor(service);
+            Mlt::Field *field = tractor.field();
+            mlt_service nextservice = mlt_service_get_producer(service.get_service());
+            mlt_service nextservicetodisconnect;
+            mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
+            QString mlt_type = mlt_properties_get(properties, "mlt_type");
+            QString resource = mlt_properties_get(properties, "mlt_service");
+            // Delete all transitions
+            while (mlt_type == "transition") {
+                nextservicetodisconnect = nextservice;
+                nextservice = mlt_service_producer(nextservice);
+                mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
+                if (nextservice == NULL) break;
+                properties = MLT_SERVICE_PROPERTIES(nextservice);
+                mlt_type = mlt_properties_get(properties, "mlt_type");
+                resource = mlt_properties_get(properties, "mlt_service");
+            }
+
+            for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
+                Mlt::Producer trackProducer(tractor.track(trackNb));
+                Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+                if (trackPlaylist.type() == playlist_type) trackPlaylist.clear();
+            }
+            delete field;
+        }
+        mlt_service_unlock(service.get_service());
+
+        qDeleteAll(m_slowmotionProducers.values());
+        m_slowmotionProducers.clear();
+
         delete m_mltProducer;
         m_mltProducer = NULL;
         emit stopped();
@@ -838,6 +996,7 @@ void Render::setSceneList(QString playlist, int position)
     if (!m_mltProducer || !m_mltProducer->is_valid()) {
         kDebug() << " WARNING - - - - -INVALID PLAYLIST: " << tmp;
         m_mltProducer = m_blackClip->cut(0, 50);
+        error = -1;
     }
     delete[] tmp;
 
@@ -873,17 +1032,18 @@ void Render::setSceneList(QString playlist, int position)
     }
 
     kDebug() << "// NEW SCENE LIST DURATION SET TO: " << m_mltProducer->get_playtime();
-    connectPlaylist();
+    if (error == 0) error = connectPlaylist();
+    else connectPlaylist();
     fillSlowMotionProducers();
 
     m_isBlocked = false;
     blockSignals(false);
-    emit refreshDocumentProducers();
+
+    return error;
     //kDebug()<<"// SETSCN LST, POS: "<<position;
     //if (position != 0) emit rendererPosition(position);
 }
 
-/** Create the producer from the MLT XML QDomDocument */
 const QString Render::sceneList()
 {
     QString playlist;
@@ -924,7 +1084,6 @@ bool Render::saveSceneList(QString path, QDomElement kdenliveData)
     return true;
 }
 
-
 void Render::saveZone(KUrl url, QString desc, QPoint zone)
 {
     kDebug() << "// SAVING CLIP ZONE, RENDER: " << m_name;
@@ -938,6 +1097,7 @@ void Render::saveZone(KUrl url, QString desc, QPoint zone)
         tmppath = decodedString(desc);
         Mlt::Playlist list;
         list.insert_at(0, prod, 0);
+        delete prod;
         list.set("title", tmppath);
         delete[] tmppath;
         xmlConsumer.connect(list);
@@ -963,24 +1123,22 @@ double Render::fps() const
     return m_fps;
 }
 
-void Render::connectPlaylist()
+int Render::connectPlaylist()
 {
-    if (!m_mltConsumer) return;
+    if (!m_mltConsumer) return -1;
     //m_mltConsumer->set("refresh", "0");
     m_mltConsumer->connect(*m_mltProducer);
     m_mltProducer->set_speed(0);
-    m_mltConsumer->start();
+    if (m_mltConsumer->start() == -1) {
+        // ARGH CONSUMER BROKEN!!!!
+        KMessageBox::error(qApp->activeWindow(), i18n("Could not create the video preview window.\nThere is something wrong with your Kdenlive install or your driver settings, please fix it."));
+        delete m_mltConsumer;
+        m_mltConsumer = NULL;
+        return -1;
+    }
     emit durationChanged(m_mltProducer->get_playtime());
+    return 0;
     //refresh();
-    /*
-     if (m_mltConsumer->start() == -1) {
-          KMessageBox::error(qApp->activeWindow(), i18n("Could not create the video preview window.\nThere is something wrong with your Kdenlive install or your driver settings, please fix it."));
-          delete m_mltConsumer;
-          m_mltConsumer = NULL;
-     }
-     else {
-             refresh();
-     }*/
 }
 
 void Render::refreshDisplay()
@@ -1020,7 +1178,7 @@ void Render::setVolume(double /*volume*/)
      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
     }*/
     refresh();
-    m_osdTimer->setSingleShot(2500);
+    //m_osdTimer->setSingleShot(2500);
 }
 
 void Render::slotOsdTimeout()
@@ -1039,14 +1197,11 @@ void Render::start()
         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
         return;
     }
-
     if (m_mltConsumer && m_mltConsumer->is_stopped()) {
         kDebug() << "-----  MONITOR: " << m_name << " WAS STOPPED";
         if (m_mltConsumer->start() == -1) {
-            KMessageBox::error(qApp->activeWindow(), i18n("Could not create the video preview window.\nThere is something wrong with your Kdenlive install or your driver settings, please fix it."));
-            delete m_mltConsumer;
-            m_mltConsumer = NULL;
-            return;
+            //KMessageBox::error(qApp->activeWindow(), i18n("Could not create the video preview window.\nThere is something wrong with your Kdenlive install or your driver settings, please fix it."));
+            kDebug(QtWarningMsg) << "/ / / / CANNOT START MONITOR";
         } else {
             kDebug() << "-----  MONITOR: " << m_name << " REFRESH";
             m_isBlocked = false;
@@ -1056,25 +1211,9 @@ void Render::start()
     m_isBlocked = false;
 }
 
-void Render::clear()
-{
-    kDebug() << " *********  RENDER CLEAR";
-    if (m_mltConsumer) {
-        //m_mltConsumer->set("refresh", 0);
-        if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
-    }
-
-    if (m_mltProducer) {
-        //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
-        m_mltProducer->set_speed(0.0);
-        delete m_mltProducer;
-        m_mltProducer = NULL;
-        emit stopped();
-    }
-}
-
 void Render::stop()
 {
+    if (m_mltProducer == NULL) return;
     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
         kDebug() << "/////////////   RENDER STOPPED: " << m_name;
         m_isBlocked = true;
@@ -1116,8 +1255,10 @@ void Render::pause()
     m_isBlocked = true;
     m_mltConsumer->set("refresh", 0);
     m_mltProducer->set_speed(0.0);
+    /*
+    The 2 lines below create a flicker loop
     emit rendererPosition(m_framePosition);
-    m_mltProducer->seek(m_framePosition);
+    m_mltProducer->seek(m_framePosition);*/
     m_mltConsumer->purge();
 }
 
@@ -1128,13 +1269,14 @@ void Render::switchPlay()
     if (m_isZoneMode) resetZoneMode();
     if (m_mltProducer->get_speed() == 0.0) {
         m_isBlocked = false;
+        if (m_name == "clip" && m_framePosition == (int) m_mltProducer->get_out()) m_mltProducer->seek(0);
         m_mltProducer->set_speed(1.0);
         m_mltConsumer->set("refresh", 1);
     } else {
         m_isBlocked = true;
         m_mltConsumer->set("refresh", 0);
         m_mltProducer->set_speed(0.0);
-        emit rendererPosition(m_framePosition);
+        //emit rendererPosition(m_framePosition);
         m_mltProducer->seek(m_framePosition);
         m_mltConsumer->purge();
         //kDebug()<<" *********  RENDER PAUSE: "<<m_mltProducer->get_speed();
@@ -1192,7 +1334,7 @@ void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
         return;
     m_isBlocked = false;
     if (!m_isZoneMode) m_originalOut = m_mltProducer->get_playtime() - 1;
-    m_mltProducer->set("out", stopTime.frames(m_fps));
+    m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
     m_mltProducer->seek((int)(startTime.frames(m_fps)));
     m_mltProducer->set_speed(1.0);
     m_mltConsumer->set("refresh", 1);
@@ -1219,10 +1361,15 @@ void Render::seekToFrame(int pos)
     refresh();
 }
 
-void Render::askForRefresh()
+void Render::seekToFrameDiff(int diff)
 {
-    // Use a Timer so that we don't refresh too much
-    m_refreshTimer->start(300);
+    //kDebug()<<" *********  RENDER SEEK TO POS";
+    if (!m_mltProducer)
+        return;
+    m_isBlocked = false;
+    resetZoneMode();
+    m_mltProducer->seek(m_mltProducer->position() + diff);
+    refresh();
 }
 
 void Render::doRefresh()
@@ -1235,7 +1382,6 @@ void Render::refresh()
 {
     if (!m_mltProducer || m_isBlocked)
         return;
-    m_refreshTimer->stop();
     if (m_mltConsumer) {
         m_mltConsumer->set("refresh", 1);
     }
@@ -1247,8 +1393,15 @@ void Render::setDropFrames(bool show)
         int dropFrames = 1;
         if (show == false) dropFrames = 0;
         m_mltConsumer->stop();
+#ifdef Q_WS_MAC
+        m_mltConsumer->set("real_time", dropFrames);
+#else
         m_mltConsumer->set("play.real_time", dropFrames);
-        m_mltConsumer->start();
+#endif
+        if (m_mltConsumer->start() == -1) {
+            kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
+        }
+
     }
 }
 
@@ -1264,13 +1417,17 @@ GenTime Render::seekPosition() const
     else return GenTime();
 }
 
+int Render::seekFramePosition() const
+{
+    if (m_mltProducer) return (int) m_mltProducer->position();
+    return 0;
+}
 
 const QString & Render::rendererName() const
 {
     return m_name;
 }
 
-
 void Render::emitFrameNumber(double position)
 {
     m_framePosition = position;
@@ -1291,14 +1448,11 @@ void Render::emitConsumerStopped()
     }
 }
 
-
-
 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
 {
     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
 }
 
-
 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
 {
     if (!m_mltProducer) {
@@ -1325,109 +1479,167 @@ void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
 }
 
-/** MLT PLAYLIST DIRECT MANIPULATON  **/
+#ifdef Q_WS_MAC
+void Render::showFrame(Mlt::Frame& frame)
+{
+    mlt_image_format format = mlt_image_rgb24a;
+    int width = 0;
+    int height = 0;
+    const uchar* image = frame.get_image(format, width, height);
+    QImage qimage(width, height, QImage::Format_ARGB32);
+    memcpy(qimage.scanLine(0), image, width * height * 4);
+    emit showImageSignal(qimage);
+}
+#endif
 
+/*
+ * MLT playlist direct manipulation.
+ */
 
-void Render::mltCheckLength()
+void Render::mltCheckLength(Mlt::Tractor *tractor)
 {
     //kDebug()<<"checking track length: "<<track<<"..........";
 
-    Mlt::Service service(m_mltProducer->get_service());
-    Mlt::Tractor tractor(service);
-
-    int trackNb = tractor.count();
+    int trackNb = tractor->count();
     int duration = 0;
     int trackDuration;
     if (trackNb == 1) {
-        Mlt::Producer trackProducer(tractor.track(0));
+        Mlt::Producer trackProducer(tractor->track(0));
         duration = trackProducer.get_playtime() - 1;
         m_mltProducer->set("out", duration);
         emit durationChanged(duration);
         return;
     }
     while (trackNb > 1) {
-        Mlt::Producer trackProducer(tractor.track(trackNb - 1));
+        Mlt::Producer trackProducer(tractor->track(trackNb - 1));
         trackDuration = trackProducer.get_playtime() - 1;
-
-        //kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
+        // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
         if (trackDuration > duration) duration = trackDuration;
         trackNb--;
     }
 
-    Mlt::Producer blackTrackProducer(tractor.track(0));
+    Mlt::Producer blackTrackProducer(tractor->track(0));
 
     if (blackTrackProducer.get_playtime() - 1 != duration) {
         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
-        if (duration > m_blackClip->get_length()) {
-            m_blackClip->set("length", duration);
-            if (blackclip) blackclip->set("length", duration);
+        if (blackclip && blackclip->is_blank()) {
+            delete blackclip;
+            blackclip = NULL;
         }
-        if (blackclip == NULL || blackclip->is_blank() || blackTrackPlaylist.count() != 1) {
+
+        if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
             blackTrackPlaylist.clear();
-            blackTrackPlaylist.append(*m_blackClip, 0, duration - 1);
-        } else blackTrackPlaylist.resize_clip(0, 0, duration - 1);
+            m_blackClip->set("length", duration + 1);
+            m_blackClip->set("out", duration);
+            blackclip = m_blackClip->cut(0, duration);
+            blackTrackPlaylist.insert_at(0, blackclip, 1);
+        } else {
+            if (duration > blackclip->parent().get_length()) {
+                blackclip->parent().set("length", duration + 1);
+                blackclip->parent().set("out", duration);
+                blackclip->set("length", duration + 1);
+            }
+            blackTrackPlaylist.resize_clip(0, 0, duration);
+        }
+
         delete blackclip;
         m_mltProducer->set("out", duration);
         emit durationChanged(duration);
     }
 }
 
-void Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod)
+Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
+{
+    if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
+
+    // We want a slowmotion producer
+    double speed = element.attribute("speed", "1.0").toDouble();
+    int strobe = element.attribute("strobe", "1").toInt();
+    QString url = QString::fromUtf8(prod->get("resource"));
+    url.append('?' + QString::number(speed));
+    if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
+    Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
+    if (!slowprod || slowprod->get_producer() == NULL) {
+        char *tmp = decodedString(url);
+        slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
+        if (strobe > 1) slowprod->set("strobe", strobe);
+        delete[] tmp;
+        QString id = prod->get("id");
+        if (id.contains('_')) id = id.section('_', 0, 0);
+        QString producerid = "slowmotion:" + id + ':' + QString::number(speed);
+        if (strobe > 1) producerid.append(':' + QString::number(strobe));
+        tmp = decodedString(producerid);
+        slowprod->set("id", tmp);
+        delete[] tmp;
+        m_slowmotionProducers.insert(url, slowprod);
+    }
+    return slowprod;
+}
+
+int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
 {
     if (m_mltProducer == NULL) {
         kDebug() << "PLAYLIST NOT INITIALISED //////";
-        return;
+        return -1;
+    }
+    if (prod == NULL) {
+        kDebug() << "Cannot insert clip without producer //////";
+        return -1;
     }
     Mlt::Producer parentProd(m_mltProducer->parent());
     if (parentProd.get_producer() == NULL) {
         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
-        return;
+        return -1;
     }
 
     Mlt::Service service(parentProd.get_service());
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return -1;
+    }
     Mlt::Tractor tractor(service);
     if (info.track > tractor.count() - 1) {
         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
-        return;
+        return -1;
     }
     mlt_service_lock(service.get_service());
     Mlt::Producer trackProducer(tractor.track(info.track));
+    int trackDuration = trackProducer.get_playtime() - 1;
     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
-
-    if (element.attribute("speed", "1.0").toDouble() != 1.0) {
-        // We want a slowmotion producer
-        double speed = element.attribute("speed", "1.0").toDouble();
-        QString url = QString::fromUtf8(prod->get("resource"));
-        url.append('?' + QString::number(speed));
-        Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
-        if (!slowprod || slowprod->get_producer() == NULL) {
-            char *tmp = decodedString(url);
-            slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
-            delete[] tmp;
-            QString id = prod->get("id");
-            if (id.contains('_')) id = id.section('_', 0, 0);
-            QString producerid = "slowmotion:" + id + ':' + QString::number(speed);
-            tmp = decodedString(producerid);
-            slowprod->set("id", tmp);
-            delete[] tmp;
-            m_slowmotionProducers.insert(url, slowprod);
-        }
-        prod = slowprod;
+    prod = checkSlowMotionProducer(prod, element);
+    if (prod == NULL || !prod->is_valid()) {
+        mlt_service_unlock(service.get_service());
+        return -1;
     }
 
-    Mlt::Producer *clip = prod->cut((int) info.cropStart.frames(m_fps), (int)(info.endPos - info.startPos + info.cropStart).frames(m_fps) - 1);
-    int newIndex = trackPlaylist.insert_at((int) info.startPos.frames(m_fps), *clip, 1);
-
+    int cutPos = (int) info.cropStart.frames(m_fps);
+    if (cutPos < 0) cutPos = 0;
+    int insertPos = (int) info.startPos.frames(m_fps);
+    int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
+    Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
+    if (overwrite && (insertPos < trackDuration)) {
+        // Replace zone with blanks
+        //trackPlaylist.split_at(insertPos, true);
+        trackPlaylist.remove_region(insertPos, cutDuration + 1);
+        int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
+        trackPlaylist.insert_blank(clipIndex, cutDuration);
+    } else if (push) {
+        trackPlaylist.split_at(insertPos, true);
+        int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
+        trackPlaylist.insert_blank(clipIndex, cutDuration);
+    }
+    int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
+    delete clip;
     /*if (QString(prod->get("transparency")).toInt() == 1)
         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
 
+    if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
     mlt_service_unlock(service.get_service());
-
-    if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength();
-    //tractor.multitrack()->refresh();
-    //tractor.refresh();
+    /*tractor.multitrack()->refresh();
+    tractor.refresh();*/
+    return 0;
 }
 
 
@@ -1437,7 +1649,10 @@ void Render::mltCutClip(int track, GenTime position)
     m_isBlocked = true;
 
     Mlt::Service service(m_mltProducer->parent().get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return;
+    }
 
     Mlt::Tractor tractor(service);
     Mlt::Producer trackProducer(tractor.track(track));
@@ -1476,6 +1691,8 @@ void Render::mltCutClip(int track, GenTime position)
     }
     Mlt::Service clipService(original->get_service());
     Mlt::Service dupService(clip->get_service());
+    delete original;
+    delete clip;
     int ct = 0;
     Mlt::Filter *filter = clipService.filter(ct);
     while (filter) {
@@ -1486,7 +1703,7 @@ void Render::mltCutClip(int track, GenTime position)
             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
             if (dup && dup->is_valid()) {
                 Mlt::Properties entries(filter->get_properties());
-                for (int i = 0;i < entries.count();i++) {
+                for (int i = 0; i < entries.count(); i++) {
                     dup->set(entries.get_name(i), entries.get(i));
                 }
                 dupService.attach(*dup);
@@ -1509,18 +1726,76 @@ void Render::mltCutClip(int track, GenTime position)
     m_isBlocked = false;
 }
 
-void Render::mltUpdateClip(ItemInfo info, QDomElement element, Mlt::Producer *prod)
+bool Render::mltUpdateClip(ItemInfo info, QDomElement element, Mlt::Producer *prod)
 {
     // TODO: optimize
-    mltRemoveClip(info.track, info.startPos);
-    mltInsertClip(info, element, prod);
+    if (prod == NULL) {
+        kDebug() << "Cannot update clip with null producer //////";
+        return false;
+    }
+    Mlt::Service service(m_mltProducer->parent().get_service());
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return false;
+    }
+    Mlt::Tractor tractor(service);
+    Mlt::Producer trackProducer(tractor.track(info.track));
+    Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+    int startPos = info.startPos.frames(m_fps);
+    int clipIndex = trackPlaylist.get_clip_index_at(startPos);
+    if (trackPlaylist.is_blank(clipIndex)) {
+        kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
+        return false;
+    }
+    mlt_service_lock(service.get_service());
+    Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
+    // keep effects
+    QList <Mlt::Filter *> filtersList;
+    Mlt::Service sourceService(clip->get_service());
+    int ct = 0;
+    Mlt::Filter *filter = sourceService.filter(ct);
+    while (filter) {
+        if (filter->get("kdenlive_ix") != 0) {
+            filtersList.append(filter);
+        }
+        ct++;
+        filter = sourceService.filter(ct);
+    }
+
+    trackPlaylist.replace_with_blank(clipIndex);
+    delete clip;
+    //if (!mltRemoveClip(info.track, info.startPos)) return false;
+    prod = checkSlowMotionProducer(prod, element);
+    if (prod == NULL || !prod->is_valid()) {
+        mlt_service_unlock(service.get_service());
+        return false;
+    }
+    Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps));
+    trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
+    delete clip2;
+
+
+    //if (mltInsertClip(info, element, prod) == -1) return false;
+    if (!filtersList.isEmpty()) {
+        clipIndex = trackPlaylist.get_clip_index_at(startPos);
+        Mlt::Producer *destclip = trackPlaylist.get_clip(clipIndex);
+        Mlt::Service destService(destclip->get_service());
+        delete destclip;
+        for (int i = 0; i < filtersList.count(); i++)
+            destService.attach(*(filtersList.at(i)));
+    }
+    mlt_service_unlock(service.get_service());
+    return true;
 }
 
 
 bool Render::mltRemoveClip(int track, GenTime position)
 {
     Mlt::Service service(m_mltProducer->parent().get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return false;
+    }
 
     Mlt::Tractor tractor(service);
     mlt_service_lock(service.get_service());
@@ -1528,9 +1803,9 @@ bool Render::mltRemoveClip(int track, GenTime position)
     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
 
-    /* // Display playlist info
-    kDebug()<<"////  BEFORE";
-    for (int i = 0; i < trackPlaylist.count(); i++) {
+    // Display playlist info
+    //kDebug() << "////  BEFORE -( " << position.frames(m_fps) << " )-------------------------------";
+    /*for (int i = 0; i < trackPlaylist.count(); i++) {
     int blankStart = trackPlaylist.clip_start(i);
     int blankDuration = trackPlaylist.clip_length(i) - 1;
     QString blk;
@@ -1539,10 +1814,13 @@ bool Render::mltRemoveClip(int track, GenTime position)
     }*/
     if (trackPlaylist.is_blank(clipIndex)) {
         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(25);
+        mlt_service_unlock(service.get_service());
         return false;
     }
+    //kDebug()<<"////  Deleting at: "<< (int) position.frames(m_fps) <<" --------------------------------------";
     m_isBlocked = true;
-    trackPlaylist.replace_with_blank(clipIndex);
+    Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
+    if (clip) delete clip;
     trackPlaylist.consolidate_blanks(0);
     /*if (QString(clip.parent().get("transparency")).toInt() == 1)
         mltDeleteTransparency((int) position.frames(m_fps), track, QString(clip.parent().get("id")).toInt());*/
@@ -1557,7 +1835,7 @@ bool Render::mltRemoveClip(int track, GenTime position)
     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
     }*/
     mlt_service_unlock(service.get_service());
-    if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength();
+    if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
     m_isBlocked = false;
     return true;
 }
@@ -1566,12 +1844,12 @@ int Render::mltGetSpaceLength(const GenTime pos, int track, bool fromBlankStart)
 {
     if (!m_mltProducer) {
         kDebug() << "PLAYLIST NOT INITIALISED //////";
-        return -1;
+        return 0;
     }
     Mlt::Producer parentProd(m_mltProducer->parent());
     if (parentProd.get_producer() == NULL) {
         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
-        return -1;
+        return 0;
     }
 
     Mlt::Service service(parentProd.get_service());
@@ -1581,7 +1859,11 @@ int Render::mltGetSpaceLength(const GenTime pos, int track, bool fromBlankStart)
     Mlt::Producer trackProducer(tractor.track(track));
     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
-    if (!trackPlaylist.is_blank(clipIndex)) return -1;
+    if (clipIndex == trackPlaylist.count()) {
+        // We are after the end of the playlist
+        return -1;
+    }
+    if (!trackPlaylist.is_blank(clipIndex)) return 0;
     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
 }
@@ -1634,12 +1916,19 @@ void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int>
         if (insertPos != -1) {
             insertPos += offset;
             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
-            if (diff > 0) trackPlaylist.insert_blank(clipIndex, diff - 1);
-            else {
+            if (diff > 0) {
+                trackPlaylist.insert_blank(clipIndex, diff - 1);
+            } else {
                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
-                if (!trackPlaylist.is_blank(clipIndex)) kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
+                if (!trackPlaylist.is_blank(clipIndex)) {
+                    kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
+                }
                 int position = trackPlaylist.clip_start(clipIndex);
-                trackPlaylist.remove_region(position, - diff - 1);
+                int blankDuration = trackPlaylist.clip_length(clipIndex);
+                diff = -diff;
+                if (blankDuration - diff == 0) {
+                    trackPlaylist.remove(clipIndex);
+                } else trackPlaylist.remove_region(position, diff);
             }
             trackPlaylist.consolidate_blanks(0);
         }
@@ -1669,14 +1958,12 @@ void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int>
             resource = mlt_properties_get(properties, "mlt_service");
         }
     } else {
-        int trackNb = tractor.count();
-        while (trackNb > 1) {
-            Mlt::Producer trackProducer(tractor.track(trackNb - 1));
+        for(int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
+            Mlt::Producer trackProducer(tractor.track(trackNb));
             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
 
-
             //int clipNb = trackPlaylist.count();
-            insertPos = trackClipStartList.value(trackNb - 1);
+            insertPos = trackClipStartList.value(trackNb);
             if (insertPos != -1) {
                 insertPos += offset;
 
@@ -1691,16 +1978,23 @@ void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int>
 
 
                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
-                if (diff > 0) trackPlaylist.insert_blank(clipIndex, diff - 1);
-                else {
-                    if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
-                    if (!trackPlaylist.is_blank(clipIndex)) kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
+                if (diff > 0) {
+                    trackPlaylist.insert_blank(clipIndex, diff - 1);
+                } else {
+                    if (!trackPlaylist.is_blank(clipIndex)) {
+                        clipIndex --;
+                    }
+                    if (!trackPlaylist.is_blank(clipIndex)) {
+                        kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
+                    }
                     int position = trackPlaylist.clip_start(clipIndex);
-                    trackPlaylist.remove_region(position, - diff - 1);
+                    int blankDuration = trackPlaylist.clip_length(clipIndex);
+                    if (diff + blankDuration == 0) {
+                        trackPlaylist.remove(clipIndex);
+                    } else trackPlaylist.remove_region(position, - diff);
                 }
                 trackPlaylist.consolidate_blanks(0);
             }
-            trackNb--;
         }
         // now move transitions
         mlt_service serv = m_mltProducer->parent().get_service();
@@ -1729,16 +2023,38 @@ void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int>
         }
     }
     mlt_service_unlock(service.get_service());
-    mltCheckLength();
+    mltCheckLength(&tractor);
     m_mltConsumer->set("refresh", 1);
 }
 
-int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt::Producer *prod)
+
+void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
+{
+    if (source == dest) return;
+    Mlt::Service sourceService(source->get_service());
+    Mlt::Service destService(dest->get_service());
+
+    // move all effects to the correct producer
+    int ct = 0;
+    Mlt::Filter *filter = sourceService.filter(ct);
+    while (filter) {
+        if (filter->get("kdenlive_ix") != 0) {
+            sourceService.detach(*filter);
+            destService.attach(*filter);
+        } else ct++;
+        filter = sourceService.filter(ct);
+    }
+}
+
+int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
 {
     m_isBlocked = true;
     int newLength = 0;
     Mlt::Service service(m_mltProducer->parent().get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return -1;
+    }
     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
     Mlt::Tractor tractor(service);
     Mlt::Producer trackProducer(tractor.track(info.track));
@@ -1747,42 +2063,57 @@ int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt
     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
     int clipLength = trackPlaylist.clip_length(clipIndex);
 
-    Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
-    if (clip == NULL) {
+    Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
+    if (original == NULL) {
         return -1;
     }
-    if (!clip->is_valid() || clip->is_blank()) {
+    if (!original->is_valid() || original->is_blank()) {
         // invalid clip
-        delete clip;
+        delete original;
         return -1;
     }
-    Mlt::Producer clipparent = clip->parent();
+    Mlt::Producer clipparent = original->parent();
     if (!clipparent.is_valid() || clipparent.is_blank()) {
         // invalid clip
-        delete clip;
+        delete original;
         return -1;
     }
-    delete clip;
+
     QString serv = clipparent.get("mlt_service");
     QString id = clipparent.get("id");
     //kDebug() << "CLIP SERVICE: " << serv;
-    if (serv == "avformat" && speed != 1.0) {
+    if (serv == "avformat" && (speed != 1.0 || strobe > 1)) {
         mlt_service_lock(service.get_service());
         QString url = QString::fromUtf8(clipparent.get("resource"));
         url.append('?' + QString::number(speed));
+        if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
         if (!slowprod || slowprod->get_producer() == NULL) {
-            char *tmp = decodedString(url);
-            slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
+            char *tmp = decodedString("framebuffer:" + url);
+            slowprod = new Mlt::Producer(*m_mltProfile, 0, tmp);
+            if (strobe > 1) slowprod->set("strobe", strobe);
             delete[] tmp;
             QString producerid = "slowmotion:" + id + ':' + QString::number(speed);
+            if (strobe > 1) producerid.append(':' + QString::number(strobe));
             tmp = decodedString(producerid);
             slowprod->set("id", tmp);
             delete[] tmp;
+            // copy producer props
+            double ar = original->parent().get_double("force_aspect_ratio");
+            if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
+            double fps = original->parent().get_double("force_fps");
+            if (fps != 0.0) slowprod->set("force_fps", fps);
+            int threads = original->parent().get_int("threads");
+            if (threads != 0) slowprod->set("threads", threads);
+            if (original->parent().get("force_progressive"))
+                slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
+            int ix = original->parent().get_int("video_index");
+            if (ix != 0) slowprod->set("video_index", ix);
             m_slowmotionProducers.insert(url, slowprod);
         }
-        trackPlaylist.replace_with_blank(clipIndex);
+        Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
         trackPlaylist.consolidate_blanks(0);
+
         // Check that the blank space is long enough for our new duration
         clipIndex = trackPlaylist.get_clip_index_at(startPos);
         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
@@ -1791,14 +2122,19 @@ int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt
             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
-        trackPlaylist.insert_at(startPos, *cut, 1);
+
+        // move all effects to the correct producer
+        mltPasteEffects(clip, cut);
+        trackPlaylist.insert_at(startPos, cut, 1);
+        delete cut;
+        delete clip;
         clipIndex = trackPlaylist.get_clip_index_at(startPos);
         newLength = trackPlaylist.clip_length(clipIndex);
         mlt_service_unlock(service.get_service());
-    } else if (speed == 1.0) {
+    } else if (speed == 1.0 && strobe < 2) {
         mlt_service_lock(service.get_service());
 
-        trackPlaylist.replace_with_blank(clipIndex);
+        Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
         trackPlaylist.consolidate_blanks(0);
 
         // Check that the blank space is long enough for our new duration
@@ -1806,13 +2142,18 @@ int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt
         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
 
         Mlt::Producer *cut;
-        GenTime oldDuration = GenTime(clipLength, m_fps);
-        GenTime newDuration = oldDuration * oldspeed;
-        if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + newDuration).frames(m_fps) > blankEnd) {
+        int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
+        if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
-            cut = prod->cut((int)(info.cropStart.frames(m_fps)), (int)(info.cropStart.frames(m_fps) + maxLength.frames(m_fps) - 1));
-        } else cut = prod->cut((int)(info.cropStart.frames(m_fps)), (int)((info.cropStart + newDuration).frames(m_fps)) - 1);
-        trackPlaylist.insert_at(startPos, *cut, 1);
+            cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
+        } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
+
+        // move all effects to the correct producer
+        mltPasteEffects(clip, cut);
+
+        trackPlaylist.insert_at(startPos, cut, 1);
+        delete cut;
+        delete clip;
         clipIndex = trackPlaylist.get_clip_index_at(startPos);
         newLength = trackPlaylist.clip_length(clipIndex);
         mlt_service_unlock(service.get_service());
@@ -1822,47 +2163,66 @@ int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt
         QString url = QString::fromUtf8(clipparent.get("resource"));
         url = url.section('?', 0, 0);
         url.append('?' + QString::number(speed));
+        if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
         if (!slowprod || slowprod->get_producer() == NULL) {
-            char *tmp = decodedString(url);
-            slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
+            char *tmp = decodedString("framebuffer:" + url);
+            slowprod = new Mlt::Producer(*m_mltProfile, 0, tmp);
             delete[] tmp;
+            slowprod->set("strobe", strobe);
             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + QString::number(speed);
+            if (strobe > 1) producerid.append(':' + QString::number(strobe));
             tmp = decodedString(producerid);
             slowprod->set("id", tmp);
             delete[] tmp;
+            // copy producer props
+            double ar = original->parent().get_double("force_aspect_ratio");
+            if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
+            double fps = original->parent().get_double("force_fps");
+            if (fps != 0.0) slowprod->set("force_fps", fps);
+            if (original->parent().get("force_progressive"))
+                slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
+            int threads = original->parent().get_int("threads");
+            if (threads != 0) slowprod->set("threads", threads);
+            int ix = original->parent().get_int("video_index");
+            if (ix != 0) slowprod->set("video_index", ix);
             m_slowmotionProducers.insert(url, slowprod);
         }
-        trackPlaylist.replace_with_blank(clipIndex);
+        Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
         trackPlaylist.consolidate_blanks(0);
 
-        GenTime oldDuration = GenTime(clipLength, m_fps);
-        GenTime newDuration = oldDuration * oldspeed / speed;
+        GenTime duration = speedIndependantInfo.cropDuration / speed;
+        int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
 
         // Check that the blank space is long enough for our new duration
         clipIndex = trackPlaylist.get_clip_index_at(startPos);
         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
 
         Mlt::Producer *cut;
-        if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + newDuration).frames(m_fps) > blankEnd) {
+        if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
-            cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
-        } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart / speed + newDuration).frames(m_fps) - 1));
+            cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
+        } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
+
+        // move all effects to the correct producer
+        mltPasteEffects(clip, cut);
 
-        trackPlaylist.insert_at(startPos, *cut, 1);
+        trackPlaylist.insert_at(startPos, cut, 1);
+        delete cut;
+        delete clip;
         clipIndex = trackPlaylist.get_clip_index_at(startPos);
         newLength = trackPlaylist.clip_length(clipIndex);
 
         mlt_service_unlock(service.get_service());
     }
-    if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength();
+    delete original;
+    if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
     m_isBlocked = false;
     return newLength;
 }
 
 bool Render::mltRemoveEffect(int track, GenTime position, QString index, bool updateIndex, bool doRefresh)
 {
-    kDebug() << "// TRYing to remove effect at: " << index;
     Mlt::Service service(m_mltProducer->parent().get_service());
     bool success = false;
     Mlt::Tractor tractor(service);
@@ -1875,6 +2235,7 @@ bool Render::mltRemoveEffect(int track, GenTime position, QString index, bool up
         return success;
     }
     Mlt::Service clipService(clip->get_service());
+    delete clip;
 //    if (tag.startsWith("ladspa")) tag = "ladspa";
     m_isBlocked = true;
     int ct = 0;
@@ -1882,7 +2243,7 @@ bool Render::mltRemoveEffect(int track, GenTime position, QString index, bool up
     while (filter) {
         if ((index == "-1" && strcmp(filter->get("kdenlive_id"), ""))  || filter->get("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
             if (clipService.detach(*filter) == 0) success = true;
-            kDebug() << " / / / DLEETED EFFECT: " << ct;
+            //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
         } else if (updateIndex) {
             // Adjust the other effects index
             if (QString(filter->get("kdenlive_ix")).toInt() > index.toInt()) filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() - 1);
@@ -1911,14 +2272,46 @@ bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList para
     }
     Mlt::Service clipService(clip->get_service());
     m_isBlocked = true;
+    int duration = clip->get_playtime();
+    bool updateIndex = false;
+    delete clip;
 
-    // temporarily remove all effects after insert point
-    QList <Mlt::Filter *> filtersList;
     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
     int ct = 0;
     Mlt::Filter *filter = clipService.filter(ct);
     while (filter) {
-        if (QString(filter->get("kdenlive_ix")).toInt() > filter_ix) {
+        if (QString(filter->get("kdenlive_ix")).toInt() == filter_ix) {
+            // A filter at that position already existed, so we will increase all indexes later
+            updateIndex = true;
+            break;
+        }
+        ct++;
+        filter = clipService.filter(ct);
+    }
+
+    if (params.paramValue("id") == "speed") {
+        // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
+        ct = 0;
+        filter = clipService.filter(ct);
+        while (filter) {
+            if (QString(filter->get("kdenlive_ix")).toInt() >= filter_ix) {
+                if (updateIndex) filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() + 1);
+            }
+            ct++;
+            filter = clipService.filter(ct);
+        }
+        m_isBlocked = false;
+        if (doRefresh) refresh();
+        return true;
+    }
+
+
+    // temporarily remove all effects after insert point
+    QList <Mlt::Filter *> filtersList;
+    ct = 0;
+    filter = clipService.filter(ct);
+    while (filter) {
+        if (QString(filter->get("kdenlive_ix")).toInt() >= filter_ix) {
             filtersList.append(filter);
             clipService.detach(*filter);
         } else ct++;
@@ -1940,7 +2333,6 @@ bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList para
         char *starttag = decodedString(params.paramValue("starttag", "start"));
         char *endtag = decodedString(params.paramValue("endtag", "end"));
         kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
-        int duration = clip->get_playtime();
         //double max = params.paramValue("max").toDouble();
         double min = params.paramValue("min").toDouble();
         double factor = params.paramValue("factor", "1").toDouble();
@@ -2006,7 +2398,7 @@ bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList para
             params.removeParam("id");
             params.removeParam("kdenlive_ix");
             params.removeParam("tag");
-            params.removeParam("disabled");
+            params.removeParam("disable");
 
             for (int j = 0; j < params.count(); j++) {
                 effectArgs.append(' ' + params.at(j).value());
@@ -2026,9 +2418,11 @@ bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList para
 
     // re-add following filters
     for (int i = 0; i < filtersList.count(); i++) {
-        clipService.attach(*(filtersList.at(i)));
+        Mlt::Filter *filter = filtersList.at(i);
+        if (updateIndex)
+            filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() + 1);
+        clipService.attach(*filter);
     }
-
     m_isBlocked = false;
     if (doRefresh) refresh();
     return true;
@@ -2041,12 +2435,12 @@ bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList par
 
     if (!params.paramValue("keyframes").isEmpty() || /*it.key().startsWith("#") || */tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
         // This is a keyframe effect, to edit it, we remove it and re-add it.
-        mltRemoveEffect(track, position, index, true);
+        mltRemoveEffect(track, position, index, false);
         bool success = mltAddEffect(track, position, params);
         return success;
     }
 
-    // create filter
+    // find filter
     Mlt::Service service(m_mltProducer->parent().get_service());
 
     Mlt::Tractor tractor(service);
@@ -2059,9 +2453,23 @@ bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList par
         return false;
     }
     Mlt::Service clipService(clip->get_service());
+    delete clip;
     m_isBlocked = true;
     int ct = 0;
     Mlt::Filter *filter = clipService.filter(ct);
+
+    /*
+    kDebug() << "EDITING FILTER: "<<index <<", "<<tag;
+    kDebug() << "EFFect stack: ++++++++++++++++++++++++++";
+    while (filter) {
+        kDebug() << "Filter: "<< filter->get("kdenlive_id") <<", IX: "<<filter->get("kdenlive_ix");
+        ct++;
+        filter = clipService.filter(ct);
+    }
+    kDebug() << "++++++++++++++++++++++++++";
+    */
+    ct = 0;
+    filter = clipService.filter(ct);
     while (filter) {
         if (filter->get("kdenlive_ix") == index) {
             break;
@@ -2071,28 +2479,14 @@ bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList par
     }
 
     if (!filter) {
-        kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT!!!!!";
+        kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
         // filter was not found, it was probably a disabled filter, so add it to the correct place...
-        int ct = 0;
-        filter = clipService.filter(ct);
-        QList <Mlt::Filter *> filtersList;
-        while (filter) {
-            if (QString(filter->get("kdenlive_ix")).toInt() > index.toInt()) {
-                filtersList.append(filter);
-                clipService.detach(*filter);
-            } else ct++;
-            filter = clipService.filter(ct);
-        }
-        bool success = mltAddEffect(track, position, params);
-
-        for (int i = 0; i < filtersList.count(); i++) {
-            clipService.attach(*(filtersList.at(i)));
-        }
 
+        bool success = mltAddEffect(track, position, params);
         m_isBlocked = false;
         return success;
     }
-
+    mlt_service_lock(service.get_service());
     for (int j = 0; j < params.count(); j++) {
         char *name = decodedString(params.at(j).name());
         char *value = decodedString(params.at(j).value());
@@ -2100,12 +2494,45 @@ bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList par
         delete[] name;
         delete[] value;
     }
+    mlt_service_unlock(service.get_service());
 
     m_isBlocked = false;
     refresh();
     return true;
 }
 
+void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
+{
+
+    kDebug() << "MOVING EFFECT FROM " << oldPos << ", TO: " << newPos;
+    Mlt::Service service(m_mltProducer->parent().get_service());
+
+    Mlt::Tractor tractor(service);
+    Mlt::Producer trackProducer(tractor.track(track));
+    Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+    //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
+    Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
+    if (!clip) {
+        kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
+        return;
+    }
+    Mlt::Service clipService(clip->get_service());
+    delete clip;
+    m_isBlocked = true;
+    int ct = 0;
+    Mlt::Filter *filter = clipService.filter(ct);
+    while (filter) {
+        int pos = QString(filter->get("kdenlive_ix")).toInt();
+        if (pos == oldPos) {
+            filter->set("kdenlive_ix", newPos);
+        } else ct++;
+        filter = clipService.filter(ct);
+    }
+
+    m_isBlocked = false;
+    refresh();
+}
+
 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
 {
 
@@ -2122,6 +2549,7 @@ void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
         return;
     }
     Mlt::Service clipService(clip->get_service());
+    delete clip;
     m_isBlocked = true;
     int ct = 0;
     QList <Mlt::Filter *> filtersList;
@@ -2210,6 +2638,7 @@ bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
     if (newDuration > clip->get_length()) {
         clip->parent().set("length", newDuration + 1);
+        clip->parent().set("out", newDuration);
         clip->set("length", newDuration + 1);
     }
     if (newDuration > clip->get_out()) {
@@ -2228,20 +2657,22 @@ bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
             // If this is not the last clip in playlist
             if (trackPlaylist.is_blank(clipIndex)) {
                 int blankStart = trackPlaylist.clip_start(clipIndex);
-                int blankDuration = trackPlaylist.clip_length(clipIndex) - 1;
-                if (diff > blankDuration) kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
-                if (diff - blankDuration == 1) {
+                int blankDuration = trackPlaylist.clip_length(clipIndex);
+                if (diff > blankDuration) {
+                    kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
+                }
+                if (diff - blankDuration == 0) {
                     trackPlaylist.remove(clipIndex);
-                } else trackPlaylist.remove_region(blankStart, diff - 1);
+                } else trackPlaylist.remove_region(blankStart, diff);
             } else {
                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
             }
         }
-    } else trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
+    } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
     trackPlaylist.consolidate_blanks(0);
     mlt_service_unlock(service.get_service());
 
-    if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength();
+    if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
@@ -2320,17 +2751,15 @@ bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
     }
     mlt_service_lock(service.get_service());
     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
-    Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
-    if (clip == NULL) {
+    if (trackPlaylist.is_blank(clipIndex)) {
         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
         mlt_service_unlock(service.get_service());
         return false;
     }
-    int previousStart = clip->get_in();
-    delete clip;
+    int previousStart = trackPlaylist.clip_start(clipIndex);
     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;
     m_isBlocked = true;
-    kDebug() << "RESIZE, old start: " << previousStart << ", PREV DUR: " << previousDuration << ", DIFF: " << moveFrame;
+    kDebug() << "RESIZE, old start: " << previousStart + moveFrame << ", " << previousStart + previousDuration;
     trackPlaylist.resize_clip(clipIndex, previousStart + moveFrame, previousStart + previousDuration);
     if (moveFrame > 0) trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
     else {
@@ -2361,76 +2790,82 @@ bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
     return true;
 }
 
-bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod)
+bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
 {
-    return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod);
+    return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
 }
 
 
-void Render::mltUpdateClipProducer(int track, int pos, Mlt::Producer *prod)
+bool Render::mltUpdateClipProducer(int track, int pos, Mlt::Producer *prod)
 {
     if (prod == NULL || !prod->is_valid()) {
         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
-        return;
+        return false;
     }
     kDebug() << "NEW PROD ID: " << prod->get("id");
     m_isBlocked++;
     kDebug() << "// TRYING TO UPDATE CLIP at: " << pos << ", TK: " << track;
-    mlt_service_lock(m_mltConsumer->get_service());
     Mlt::Service service(m_mltProducer->parent().get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
-
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return false;
+    }
+    mlt_service_lock(service.get_service());
     Mlt::Tractor tractor(service);
     Mlt::Producer trackProducer(tractor.track(track));
     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
-    int clipIndex = trackPlaylist.get_clip_index_at(pos + 1);
-    Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
-    if (clipProducer.is_blank()) {
+    int clipIndex = trackPlaylist.get_clip_index_at(pos);
+    Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
+    if (clipProducer == NULL || clipProducer->is_blank()) {
         kDebug() << "// ERROR UPDATING CLIP PROD";
-        mlt_service_unlock(m_mltConsumer->get_service());
+        delete clipProducer;
+        mlt_service_unlock(service.get_service());
         m_isBlocked--;
-        return;
+        return false;
     }
-    Mlt::Producer *clip = prod->cut(clipProducer.get_in(), clipProducer.get_out());
-
-    // move all effects to the correct producer
-    Mlt::Service clipService(clipProducer.get_service());
-    Mlt::Service newClipService(clip->get_service());
-
-    int ct = 0;
-    Mlt::Filter *filter = clipService.filter(ct);
-    while (filter) {
-        if (filter->get("kdenlive_ix") != 0) {
-            clipService.detach(*filter);
-            newClipService.attach(*filter);
-        } else ct++;
-        filter = clipService.filter(ct);
+    Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
+    if (!clip || !clip->is_valid()) {
+        if (clip) delete clip;
+        delete clipProducer;
+        mlt_service_unlock(service.get_service());
+        m_isBlocked--;
+        return false;
     }
-
+    // move all effects to the correct producer
+    mltPasteEffects(clipProducer, clip);
     trackPlaylist.insert_at(pos, clip, 1);
-    mlt_service_unlock(m_mltConsumer->get_service());
+    delete clip;
+    delete clipProducer;
+    mlt_service_unlock(service.get_service());
     m_isBlocked--;
+    return true;
 }
 
-bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod)
+bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
 {
     m_isBlocked++;
 
     Mlt::Service service(m_mltProducer->parent().get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return false;
+    }
 
     Mlt::Tractor tractor(service);
     mlt_service_lock(service.get_service());
     Mlt::Producer trackProducer(tractor.track(startTrack));
     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
-    int clipIndex = trackPlaylist.get_clip_index_at(moveStart + 1);
+    int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
     kDebug() << "//////  LOOKING FOR CLIP TO MOVE, INDEX: " << clipIndex;
     bool checkLength = false;
     if (endTrack == startTrack) {
-        Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
-        if (!trackPlaylist.is_blank_at(moveEnd) || clipProducer.is_blank()) {
+        Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
+        if ((!overwrite && !trackPlaylist.is_blank_at(moveEnd)) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
             // error, destination is not empty
-            if (!trackPlaylist.is_blank_at(moveEnd)) trackPlaylist.insert_at(moveStart, clipProducer, 1);
+            if (clipProducer) {
+                if (!trackPlaylist.is_blank_at(moveEnd) && clipProducer->is_valid()) trackPlaylist.insert_at(moveStart, clipProducer, 1);
+                delete clipProducer;
+            }
             //int ix = trackPlaylist.get_clip_index_at(moveEnd);
             kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
             mlt_service_unlock(service.get_service());
@@ -2438,7 +2873,14 @@ bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEn
             return false;
         } else {
             trackPlaylist.consolidate_blanks(0);
+            if (overwrite) {
+                trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
+                int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
+                trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
+            }
             int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
+            trackPlaylist.consolidate_blanks(1);
+            delete clipProducer;
             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
             mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
             }*/
@@ -2448,16 +2890,17 @@ bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEn
     } else {
         Mlt::Producer destTrackProducer(tractor.track(endTrack));
         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
-        if (!destTrackPlaylist.is_blank_at(moveEnd)) {
+        if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
             // error, destination is not empty
             mlt_service_unlock(service.get_service());
             m_isBlocked--;
             return false;
         } else {
-            Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
-            if (clipProducer.is_blank()) {
+            Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
+            if (!clipProducer || clipProducer->is_blank()) {
                 // error, destination is not empty
                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
+                if (clipProducer) delete clipProducer;
                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
                 mlt_service_unlock(service.get_service());
                 m_isBlocked--;
@@ -2467,35 +2910,38 @@ bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEn
             destTrackPlaylist.consolidate_blanks(1);
             Mlt::Producer *clip;
             // check if we are moving a slowmotion producer
-            QString serv = clipProducer.parent().get("mlt_service");
-            QString currentid = clipProducer.parent().get("id");
+            QString serv = clipProducer->parent().get("mlt_service");
+            QString currentid = clipProducer->parent().get("id");
             if (serv == "framebuffer" || currentid.endsWith("_video")) {
-                clip = &clipProducer;
+                clip = clipProducer;
             } else {
                 if (prod == NULL) {
                     // Special case: prod is null when using placeholder clips.
                     // in that case, use the producer existing in playlist. Note that
                     // it will bypass the one producer per track logic and might cause
                     // Sound cracks if clip is moved so that it overlaps another copy of itself
-                    clip = clipProducer.cut(clipProducer.get_in(), clipProducer.get_out());
-                } else clip = prod->cut(clipProducer.get_in(), clipProducer.get_out());
+                    clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
+                } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
             }
 
             // move all effects to the correct producer
-            Mlt::Service clipService(clipProducer.get_service());
-            Mlt::Service newClipService(clip->get_service());
-
-            int ct = 0;
-            Mlt::Filter *filter = clipService.filter(ct);
-            while (filter) {
-                if (filter->get("kdenlive_ix") != 0) {
-                    clipService.detach(*filter);
-                    newClipService.attach(*filter);
-                } else ct++;
-                filter = clipService.filter(ct);
+            mltPasteEffects(clipProducer, clip);
+
+            if (overwrite) {
+                destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
+                int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
+                destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
             }
 
             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
+
+            if (clip == clipProducer) {
+                delete clip;
+                clip = NULL;
+            } else {
+                delete clip;
+                delete clipProducer;
+            }
             destTrackPlaylist.consolidate_blanks(0);
             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
                 kDebug() << "//////// moving clip transparency";
@@ -2506,47 +2952,79 @@ bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEn
         }
     }
     mlt_service_unlock(service.get_service());
-    if (checkLength) mltCheckLength();
+    if (checkLength) mltCheckLength(&tractor);
     m_isBlocked--;
     //askForRefresh();
     //m_mltConsumer->set("refresh", 1);
     return true;
 }
 
+
+QList <int> Render::checkTrackSequence(int track)
+{
+    QList <int> list;
+    Mlt::Service service(m_mltProducer->parent().get_service());
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return list;
+    }
+    Mlt::Tractor tractor(service);
+    mlt_service_lock(service.get_service());
+    Mlt::Producer trackProducer(tractor.track(track));
+    Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
+    int clipNb = trackPlaylist.count();
+    //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
+    for (int i = 0; i < clipNb; i++) {
+        Mlt::Producer *c = trackPlaylist.get_clip(i);
+        int pos = trackPlaylist.clip_start(i);
+        if (!list.contains(pos)) list.append(pos);
+        pos += c->get_playtime();
+        if (!list.contains(pos)) list.append(pos);
+        delete c;
+    }
+    return list;
+}
+
 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
 {
     int new_in = (int)newIn.frames(m_fps);
     int new_out = (int)newOut.frames(m_fps) - 1;
     if (new_in >= new_out) return false;
 
-    mlt_service serv = m_mltProducer->parent().get_service();
-    m_isBlocked++;
-    mlt_service_lock(serv);
-    //m_mltConsumer->set("refresh", 0);
+    Mlt::Service service(m_mltProducer->parent().get_service());
+    Mlt::Tractor tractor(service);
+    Mlt::Field *field = tractor.field();
 
+    m_isBlocked++;
+    mlt_service_lock(service.get_service());
 
-    mlt_service nextservice = mlt_service_get_producer(serv);
+    mlt_service nextservice = mlt_service_get_producer(service.get_service());
     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
     QString mlt_type = mlt_properties_get(properties, "mlt_type");
     QString resource = mlt_properties_get(properties, "mlt_service");
     int old_pos = (int)(oldIn.frames(m_fps) + oldOut.frames(m_fps)) / 2;
+    bool found = false;
 
     while (mlt_type == "transition") {
-        mlt_transition tr = (mlt_transition) nextservice;
-        int currentTrack = mlt_transition_get_b_track(tr);
-        int currentIn = (int) mlt_transition_get_in(tr);
-        int currentOut = (int) mlt_transition_get_out(tr);
+        Mlt::Transition transition((mlt_transition) nextservice);
+        int currentTrack = transition.get_b_track();
+        int currentIn = (int) transition.get_in();
+        int currentOut = (int) transition.get_out();
 
         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
-            mlt_transition_set_in_and_out(tr, new_in, new_out);
+            found = true;
             if (newTrack - startTrack != 0) {
-                //kDebug() << "///// TRANSITION CHANGE TRACK. CUrrent (b): " << currentTrack << 'x' << mlt_transition_get_a_track(tr) << ", NEw: " << newTrack << 'x' << newTransitionTrack;
-
-                mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
-                mlt_properties_set_int(properties, "a_track", newTransitionTrack);
-                mlt_properties_set_int(properties, "b_track", newTrack);
-                //kDebug() << "set new start & end :" << new_in << new_out<< "TR OFFSET: "<<trackOffset<<", TRACKS: "<<mlt_transition_get_a_track(tr)<<'x'<<mlt_transition_get_b_track(tr);
-            }
+                Mlt::Properties trans_props(transition.get_properties());
+                char *tmp = decodedString(transition.get("mlt_service"));
+                Mlt::Transition new_transition(*m_mltProfile, tmp);
+                delete[] tmp;
+                Mlt::Properties new_trans_props(new_transition.get_properties());
+                new_trans_props.inherit(trans_props);
+                new_transition.set_in_and_out(new_in, new_out);
+                field->disconnect_service(transition);
+                mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
+                //field->plant_transition(new_transition, newTransitionTrack, newTrack);
+            } else transition.set_in_and_out(new_in, new_out);
             break;
         }
         nextservice = mlt_service_producer(nextservice);
@@ -2555,20 +3033,62 @@ bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int n
         mlt_type = mlt_properties_get(properties, "mlt_type");
         resource = mlt_properties_get(properties, "mlt_service");
     }
-    mlt_service_unlock(serv);
+    mlt_service_unlock(service.get_service());
     m_isBlocked--;
-    //askForRefresh();
+    refresh();
     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
-    return true;
+    return found;
+}
+
+
+void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
+{
+    mlt_service nextservice = mlt_service_get_producer(field->get_service());
+    mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
+    QString mlt_type = mlt_properties_get(properties, "mlt_type");
+    QString resource = mlt_properties_get(properties, "mlt_service");
+    QList <Mlt::Transition *> trList;
+
+    while (mlt_type == "transition") {
+        Mlt::Transition transition((mlt_transition) nextservice);
+        int aTrack = transition.get_a_track();
+        int bTrack = transition.get_b_track();
+        if (resource != "mix" && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
+            Mlt::Properties trans_props(transition.get_properties());
+            char *tmp = decodedString(transition.get("mlt_service"));
+            Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, tmp);
+            delete[] tmp;
+            Mlt::Properties new_trans_props(cp->get_properties());
+            new_trans_props.inherit(trans_props);
+            trList.append(cp);
+            field->disconnect_service(transition);
+        }
+        //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
+
+        nextservice = mlt_service_producer(nextservice);
+        if (nextservice == NULL) break;
+        properties = MLT_SERVICE_PROPERTIES(nextservice);
+        mlt_type = mlt_properties_get(properties, "mlt_type");
+        resource = mlt_properties_get(properties, "mlt_service");
+    }
+
+    field->plant_transition(tr, a_track, b_track);
+
+    // re-add upper transitions
+    for (int i = 0; i < trList.count(); i++) {
+        // kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
+        field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
+    }
 }
 
-void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
+void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
 {
-    if (oldTag == tag) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
+    if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
     else {
         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
-        mltAddTransition(tag, a_track, b_track, in, out, xml);
+        mltAddTransition(tag, a_track, b_track, in, out, xml, false);
     }
+    refresh();
     //mltSavePlaylist();
 }
 
@@ -2578,7 +3098,6 @@ void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, G
     mlt_service_lock(serv);
     m_isBlocked++;
 
-
     mlt_service nextservice = mlt_service_get_producer(serv);
     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
     QString mlt_type = mlt_properties_get(properties, "mlt_type");
@@ -2601,6 +3120,11 @@ void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, G
             QString key;
             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
+            mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
+            // update the transition id in case it uses the same MLT service but different Kdenlive id
+            char *tmp = decodedString(xml.attribute("id"));
+            mlt_properties_set(transproperties, "kdenlive_id", tmp);
+            delete[] tmp;
             if (currentBTrack != a_track) {
                 mlt_properties_set_int(properties, "a_track", a_track);
             }
@@ -2675,7 +3199,7 @@ QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
 {
     QDomNodeList attribs = xml.elementsByTagName("parameter");
     QMap<QString, QString> map;
-    for (int i = 0;i < attribs.count();i++) {
+    for (int i = 0; i < attribs.count(); i++) {
         QDomElement e = attribs.item(i).toElement();
         QString name = e.attribute("name");
         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
@@ -2697,7 +3221,7 @@ QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
             if (values.size() > 0)
                 txtNeu << (int)values[0].toDouble();
             int i = 0;
-            for (i = 0;i < separators.size() && i + 1 < values.size();i++) {
+            for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
                 txtNeu << separators[i];
                 txtNeu << (int)(values[i+1].toDouble());
             }
@@ -2847,7 +3371,7 @@ void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int
 }
 
 
-bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool /*do_refresh*/)
+bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
 {
     if (in >= out) return false;
     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
@@ -2876,10 +3400,11 @@ bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in,
         delete[] name;
         delete[] value;
     }
-    // attach filter to the clip
-    field->plant_transition(*transition, a_track, b_track);
+    // attach transition
+    mltPlantTransition(field, *transition, a_track, b_track);
+    // field->plant_transition(*transition, a_track, b_track);
     delete[] transId;
-    refresh();
+    if (do_refresh) refresh();
     return true;
 }
 
@@ -2895,9 +3420,10 @@ void Render::mltSavePlaylist()
     fileConsumer.start();
 }
 
-QList <Mlt::Producer *> Render::producersList()
+const QList <Mlt::Producer *> Render::producersList()
 {
     QList <Mlt::Producer *> prods;
+    if (m_mltProducer == NULL) return prods;
     Mlt::Service service(m_mltProducer->parent().get_service());
     if (service.type() != tractor_type) return prods;
     Mlt::Tractor tractor(service);
@@ -2928,6 +3454,7 @@ QList <Mlt::Producer *> Render::producersList()
 
 void Render::fillSlowMotionProducers()
 {
+    if (m_mltProducer == NULL) return;
     Mlt::Service service(m_mltProducer->parent().get_service());
     if (service.type() != tractor_type) return;
 
@@ -2948,6 +3475,8 @@ void Render::fillSlowMotionProducers()
                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
                     // this is a slowmotion producer, add it to the list
                     QString url = QString::fromUtf8(nprod->get("resource"));
+                    int strobe = nprod->get_int("strobe");
+                    if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
                     if (!m_slowmotionProducers.contains(url)) {
                         m_slowmotionProducers.insert(url, nprod);
                     }
@@ -2965,7 +3494,10 @@ void Render::mltInsertTrack(int ix, bool videoTrack)
 
     Mlt::Service service(m_mltProducer->parent().get_service());
     mlt_service_lock(service.get_service());
-    if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
+    if (service.type() != tractor_type) {
+        kWarning() << "// TRACTOR PROBLEM";
+        return;
+    }
 
     Mlt::Tractor tractor(service);
 
@@ -3062,7 +3594,13 @@ void Render::mltDeleteTrack(int ix)
             int a_track = mappedProps.value("a_track").toInt();
             int b_track = mappedProps.value("b_track").toInt();
             if (a_track > 0 && a_track >= ix) a_track --;
-            if (b_track > 0 && b_track >= ix) b_track --;
+            if (b_track == ix) {
+                // transition was on the deleted track, so remove it
+                tractor.removeChild(transitions.at(i));
+                i--;
+                continue;
+            }
+            if (b_track > 0 && b_track > ix) b_track --;
             for (int j = 0; j < props.count(); j++) {
                 QDomElement f = props.at(j).toElement();
                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
@@ -3074,7 +3612,17 @@ void Render::mltDeleteTrack(int ix)
     tractor.removeChild(track);
     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
     setSceneList(doc.toString(), m_framePosition);
-    mltCheckLength();
+
+    /*    if (m_mltProducer != NULL) {
+            Mlt::Producer parentProd(m_mltProducer->parent());
+            if (parentProd.get_producer() != NULL) {
+                Mlt::Service service(parentProd.get_service());
+                if (service.type() == tractor_type) {
+                    Mlt::Tractor tractor(service);
+                    mltCheckLength(&tractor);
+                }
+            }
+        }*/
 }
 
 
@@ -3093,11 +3641,105 @@ void Render::updatePreviewSettings()
     int pos = 0;
     if (m_mltProducer) {
         pos = m_mltProducer->position();
-        delete m_mltProducer;
     }
-    m_mltProducer = NULL;
+
     setSceneList(scene, pos);
 }
 
+
+QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
+{
+    // Update all frame positions to the new fps value
+    //WARNING: there are probably some effects or other that hold a frame value
+    // as parameter and will also need to be updated here!
+    QDomDocument doc;
+    doc.setContent(scene);
+
+    double factor = new_fps / current_fps;
+    QDomNodeList producers = doc.elementsByTagName("producer");
+    for (int i = 0; i < producers.count(); i++) {
+        QDomElement prod = producers.at(i).toElement();
+        prod.removeAttribute("in");
+        prod.removeAttribute("out");
+
+        QDomNodeList props = prod.childNodes();
+        for (int j = 0; j < props.count(); j++) {
+            QDomElement param =  props.at(j).toElement();
+            QString paramName = param.attribute("name");
+            if (paramName.startsWith("meta.") || paramName == "length") {
+                prod.removeChild(props.at(j));
+                j--;
+            }
+        }
+    }
+
+    QDomNodeList entries = doc.elementsByTagName("entry");
+    for (int i = 0; i < entries.count(); i++) {
+        QDomElement entry = entries.at(i).toElement();
+        int in = entry.attribute("in").toInt();
+        int out = entry.attribute("out").toInt();
+        in = factor * in + 0.5;
+        out = factor * out + 0.5;
+        entry.setAttribute("in", in);
+        entry.setAttribute("out", out);
+    }
+
+    QDomNodeList blanks = doc.elementsByTagName("blank");
+    for (int i = 0; i < blanks.count(); i++) {
+        QDomElement blank = blanks.at(i).toElement();
+        int length = blank.attribute("length").toInt();
+        length = factor * length + 0.5;
+        blank.setAttribute("length", QString::number(length));
+    }
+
+    QDomNodeList filters = doc.elementsByTagName("filter");
+    for (int i = 0; i < filters.count(); i++) {
+        QDomElement filter = filters.at(i).toElement();
+        int in = filter.attribute("in").toInt();
+        int out = filter.attribute("out").toInt();
+        in = factor * in + 0.5;
+        out = factor * out + 0.5;
+        filter.setAttribute("in", in);
+        filter.setAttribute("out", out);
+    }
+
+    QDomNodeList transitions = doc.elementsByTagName("transition");
+    for (int i = 0; i < transitions.count(); i++) {
+        QDomElement transition = transitions.at(i).toElement();
+        int in = transition.attribute("in").toInt();
+        int out = transition.attribute("out").toInt();
+        in = factor * in + 0.5;
+        out = factor * out + 0.5;
+        transition.setAttribute("in", in);
+        transition.setAttribute("out", out);
+        QDomNodeList props = transition.childNodes();
+        for (int j = 0; j < props.count(); j++) {
+            QDomElement param =  props.at(j).toElement();
+            QString paramName = param.attribute("name");
+            if (paramName == "geometry") {
+                QString geom = param.firstChild().nodeValue();
+                QStringList keys = geom.split(';');
+                QStringList newKeys;
+                for (int k = 0; k < keys.size(); ++k) {
+                    if (keys.at(k).contains('=')) {
+                        int pos = keys.at(k).section('=', 0, 0).toInt();
+                        pos = factor * pos + 0.5;
+                        newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
+                    } else newKeys.append(keys.at(k));
+                }
+                param.firstChild().setNodeValue(newKeys.join(";"));
+            }
+        }
+    }
+    QDomElement tractor = doc.elementsByTagName("tractor").at(0).toElement();
+    int out = tractor.attribute("out").toInt();
+    out = factor * out + 0.5;
+    tractor.setAttribute("out", out);
+    emit durationChanged(out);
+
+    //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
+    return doc.toString();
+}
+
 #include "renderer.moc"