]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Fix freeze on split audio and other stuff (bad service locking)
[kdenlive] / src / renderer.cpp
1 /***************************************************************************
2                         krender.cpp  -  description
3                            -------------------
4   begin                : Fri Nov 22 2002
5   copyright            : (C) 2002 by Jason Wood
6   email                : jasonwood@blueyonder.co.uk
7   copyright            : (C) 2005 Lucio Flavio Correa
8   email                : lucio.correa@gmail.com
9   copyright            : (C) Marco Gittler
10   email                : g.marco@freenet.de
11   copyright            : (C) 2006 Jean-Baptiste Mardelle
12   email                : jb@kdenlive.org
13
14 ***************************************************************************/
15
16 /***************************************************************************
17  *                                                                         *
18  *   This program is free software; you can redistribute it and/or modify  *
19  *   it under the terms of the GNU General Public License as published by  *
20  *   the Free Software Foundation; either version 2 of the License, or     *
21  *   (at your option) any later version.                                   *
22  *                                                                         *
23  ***************************************************************************/
24
25
26 #include "renderer.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "definitions.h"
30 #include "slideshowclip.h"
31 #include "profilesdialog.h"
32 #include "blackmagic/devices.h"
33
34 #include <mlt++/Mlt.h>
35
36 #include <KDebug>
37 #include <KStandardDirs>
38 #include <KMessageBox>
39 #include <KLocale>
40 #include <KTemporaryFile>
41
42 #include <QTimer>
43 #include <QDir>
44 #include <QString>
45 #include <QApplication>
46 #include <QtConcurrentRun>
47
48 #include <cstdlib>
49 #include <cstdarg>
50
51 #include <QDebug>
52
53
54 static void kdenlive_callback(void* /*ptr*/, int level, const char* fmt, va_list vl)
55 {
56 //     kDebug() << "log level" << level << QString().vsprintf(fmt, vl).simplified();
57     if (level > MLT_LOG_ERROR) return;
58     QString error;
59     QApplication::postEvent(qApp->activeWindow(), new MltErrorEvent(error.vsprintf(fmt, vl).simplified()));
60     va_end(vl);
61 }
62
63
64 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr)
65 {
66     // detect if the producer has finished playing. Is there a better way to do it?
67     self->emitFrameNumber();
68     Mlt::Frame frame(frame_ptr);
69     if (!frame.is_valid()) return;
70     if (self->sendFrameForAnalysis && frame_ptr->convert_image) {
71         self->emitFrameUpdated(frame);
72     }
73     if (self->analyseAudio) {
74         self->showAudio(frame);
75     }
76     if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
77         self->pause();
78         self->emitConsumerStopped();
79     }
80 }
81
82
83 static void consumer_paused(mlt_consumer, Render * self, mlt_frame /*frame_ptr*/)
84 {
85     // detect if the producer has finished playing. Is there a better way to do it?
86     self->emitConsumerStopped();
87 }
88
89
90 static void consumer_gl_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr)
91 {
92     // detect if the producer has finished playing. Is there a better way to do it?
93     Mlt::Frame frame(frame_ptr);
94     self->showFrame(frame);
95     if (frame.get_double("_speed") == 0.0) {
96         self->emitConsumerStopped();
97     } else if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
98         self->pause();
99         self->emitConsumerStopped();
100     }
101 }
102
103 Render::Render(const QString & rendererName, int winid, QString profile, QWidget *parent) :
104     AbstractRender(rendererName, parent),
105     analyseAudio(KdenliveSettings::monitor_audio()),
106     m_name(rendererName),
107     m_mltConsumer(NULL),
108     m_mltProducer(NULL),
109     m_mltProfile(NULL),
110     m_externalConsumer(false),
111     m_isZoneMode(false),
112     m_isLoopMode(false),
113     m_isSplitView(false),
114     m_blackClip(NULL),
115     m_winid(winid)
116 {
117     if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
118     buildConsumer(profile);
119     m_mltProducer = m_blackClip->cut(0, 1);
120     m_mltConsumer->connect(*m_mltProducer);
121     m_mltProducer->set_speed(0.0);
122 }
123
124 Render::~Render()
125 {
126     closeMlt();
127     delete m_mltProfile;
128 }
129
130
131 void Render::closeMlt()
132 {       
133     //delete m_osdTimer;
134     m_requestList.clear();
135     m_infoThread.waitForFinished();
136     if (m_mltConsumer) delete m_mltConsumer;
137     if (m_mltProducer) delete m_mltProducer;
138     /*if (m_mltProducer) {
139         Mlt::Service service(m_mltProducer->parent().get_service());
140         service.lock();
141
142         if (service.type() == tractor_type) {
143             Mlt::Tractor tractor(service);
144             Mlt::Field *field = tractor.field();
145             mlt_service nextservice = mlt_service_get_producer(service.get_service());
146             mlt_service nextservicetodisconnect;
147             mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
148             QString mlt_type = mlt_properties_get(properties, "mlt_type");
149             QString resource = mlt_properties_get(properties, "mlt_service");
150             // Delete all transitions
151             while (mlt_type == "transition") {
152                 nextservicetodisconnect = nextservice;
153                 nextservice = mlt_service_producer(nextservice);
154                 mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
155                 if (nextservice == NULL) break;
156                 properties = MLT_SERVICE_PROPERTIES(nextservice);
157                 mlt_type = mlt_properties_get(properties, "mlt_type");
158                 resource = mlt_properties_get(properties, "mlt_service");
159             }
160
161             delete field;
162             field = NULL;
163         }
164         service.unlock();
165     }*/
166
167     kDebug() << "// // // CLOSE RENDERER " << m_name;
168     if (m_blackClip) delete m_blackClip;
169     //delete m_osdInfo;
170 }
171
172 void Render::slotSwitchFullscreen()
173 {
174     if (m_mltConsumer) m_mltConsumer->set("full_screen", 1);
175 }
176
177 void Render::buildConsumer(const QString &profileName)
178 {
179     delete m_blackClip;
180     m_blackClip = NULL;
181
182     //TODO: uncomment following line when everything is clean
183     // uncommented Feb 2011 --Granjow
184     if (m_mltProfile) delete m_mltProfile;
185     m_activeProfile = profileName;
186     char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
187     setenv("MLT_PROFILE", tmp, 1);
188     m_mltProfile = new Mlt::Profile(tmp);
189     m_mltProfile->set_explicit(true);
190     kDebug()<<"// *********  PROFILE AR: "<<m_mltProfile->dar();
191     delete[] tmp;
192
193     m_blackClip = new Mlt::Producer(*m_mltProfile, "colour", "black");
194     m_blackClip->set("id", "black");
195     m_blackClip->set("mlt_type", "producer");
196
197     if (KdenliveSettings::external_display() && m_name != "clip") {
198         // Use blackmagic card for video output
199         QMap< QString, QString > profileProperties = ProfilesDialog::getSettingsFromFile(profileName);
200         int device = KdenliveSettings::blackmagic_output_device();
201         if (device >= 0) {
202             if (BMInterface::isSupportedProfile(device, profileProperties)) {
203                 QString decklink = "decklink:" + QString::number(KdenliveSettings::blackmagic_output_device());
204                 tmp = qstrdup(decklink.toUtf8().constData());
205                 m_mltConsumer = new Mlt::Consumer(*m_mltProfile, tmp);
206                 delete[] tmp;
207                 if (m_mltConsumer->is_valid()) {
208                     m_externalConsumer = true;
209                     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
210                     m_mltConsumer->set("terminate_on_pause", 0);
211                     m_mltConsumer->set("deinterlace_method", "onefield");
212                     m_mltConsumer->set("real_time", KdenliveSettings::mltthreads());
213                     mlt_log_set_callback(kdenlive_callback);
214                 }
215                 if (m_mltConsumer && m_mltConsumer->is_valid()) return;
216             } else KMessageBox::informationList(qApp->activeWindow(), i18n("Your project's profile %1 is not compatible with the blackmagic output card. Please see supported profiles below. Switching to normal video display.", m_mltProfile->description()), BMInterface::supportedModes(KdenliveSettings::blackmagic_output_device()));
217         }
218     }
219     m_externalConsumer = false;
220     QString videoDriver = KdenliveSettings::videodrivername();
221     if (!videoDriver.isEmpty()) {
222         if (videoDriver == "x11_noaccel") {
223             setenv("SDL_VIDEO_YUV_HWACCEL", "0", 1);
224             videoDriver = "x11";
225         } else {
226             unsetenv("SDL_VIDEO_YUV_HWACCEL");
227         }
228     }
229     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
230
231     //m_mltConsumer->set("fullscreen", 1);
232     if (m_winid == 0) {
233         // OpenGL monitor
234         m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_audio");
235         m_mltConsumer->set("preview_off", 1);
236         m_mltConsumer->set("preview_format", mlt_image_rgb24a);
237         m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_gl_frame_show);
238     } else {
239         m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_preview");
240         // FIXME: the event object returned by the listen gets leaked...
241         m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
242         m_mltConsumer->listen("consumer-sdl-paused", this, (mlt_listener) consumer_paused);
243         m_mltConsumer->set("window_id", m_winid);
244     }
245     m_mltConsumer->set("resize", 1);
246     m_mltConsumer->set("terminate_on_pause", 1);
247     m_mltConsumer->set("window_background", KdenliveSettings::window_background().name().toUtf8().constData());
248     m_mltConsumer->set("rescale", "nearest");
249     mlt_log_set_callback(kdenlive_callback);
250
251     QString audioDevice = KdenliveSettings::audiodevicename();
252     if (!audioDevice.isEmpty())
253         m_mltConsumer->set("audio_device", audioDevice.toUtf8().constData());
254
255     if (!videoDriver.isEmpty())
256         m_mltConsumer->set("video_driver", videoDriver.toUtf8().constData());
257
258     QString audioDriver = KdenliveSettings::audiodrivername();
259
260     /*
261     // Disabled because the "auto" detected driver was sometimes wrong
262     if (audioDriver.isEmpty())
263         audioDriver = KdenliveSettings::autoaudiodrivername();
264     */
265
266     if (!audioDriver.isEmpty())
267         m_mltConsumer->set("audio_driver", audioDriver.toUtf8().constData());
268
269     m_mltConsumer->set("progressive", 1);
270     m_mltConsumer->set("audio_buffer", 1024);
271     m_mltConsumer->set("frequency", 48000);
272     m_mltConsumer->set("real_time", KdenliveSettings::mltthreads());
273 }
274
275 Mlt::Producer *Render::invalidProducer(const QString &id)
276 {
277     Mlt::Producer *clip;
278     QString txt = "+" + i18n("Missing clip") + ".txt";
279     char *tmp = qstrdup(txt.toUtf8().constData());
280     clip = new Mlt::Producer(*m_mltProfile, tmp);
281     delete[] tmp;
282     if (clip == NULL) clip = new Mlt::Producer(*m_mltProfile, "colour", "red");
283     else {
284         clip->set("bgcolour", "0xff0000ff");
285         clip->set("pad", "10");
286     }
287     clip->set("id", id.toUtf8().constData());
288     clip->set("mlt_type", "producer");
289     return clip;
290 }
291
292 int Render::resetProfile(const QString &profileName, bool dropSceneList)
293 {
294     QString scene;
295     if (!dropSceneList) scene = sceneList();
296     if (m_mltConsumer) {
297         if (m_externalConsumer == KdenliveSettings::external_display()) {
298             if (KdenliveSettings::external_display() && m_activeProfile == profileName) return 1;
299             QString videoDriver = KdenliveSettings::videodrivername();
300             QString currentDriver = m_mltConsumer->get("video_driver");
301             if (getenv("SDL_VIDEO_YUV_HWACCEL") != NULL && currentDriver == "x11") currentDriver = "x11_noaccel";
302             QString background = KdenliveSettings::window_background().name();
303             QString currentBackground = m_mltConsumer->get("window_background");
304             if (m_activeProfile == profileName && currentDriver == videoDriver && background == currentBackground) {
305                 kDebug() << "reset to same profile, nothing to do";
306                 return 1;
307             }
308         }
309
310         if (m_isSplitView) slotSplitView(false);
311         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
312         m_mltConsumer->purge();
313         delete m_mltConsumer;
314         m_mltConsumer = NULL;
315     }
316     int pos = 0;
317     double current_fps = m_mltProfile->fps();
318     double current_dar = m_mltProfile->dar();
319     delete m_blackClip;
320     m_blackClip = NULL;
321     m_requestList.clear();
322     m_infoThread.waitForFinished();
323
324     if (m_mltProducer) {
325         pos = m_mltProducer->position();
326
327         Mlt::Service service(m_mltProducer->get_service());
328         if (service.type() == tractor_type) {
329             Mlt::Tractor tractor(service);
330             for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
331                 Mlt::Producer trackProducer(tractor.track(trackNb));
332                 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
333                 trackPlaylist.clear();
334             }
335         }
336
337         delete m_mltProducer;
338     }
339     m_mltProducer = NULL;
340     buildConsumer(profileName);
341     double new_fps = m_mltProfile->fps();
342     double new_dar = m_mltProfile->dar();
343     
344     if (!dropSceneList) {
345         // We need to recover our playlist
346         if (current_fps != new_fps) {
347             // fps changed, we must update the scenelist positions
348             scene = updateSceneListFps(current_fps, new_fps, scene);
349         }
350         setSceneList(scene, pos);
351         // producers have changed (different profile), so reset them...
352         emit refreshDocumentProducers(new_dar != current_dar, current_fps != new_fps);
353     }
354     return 1;
355 }
356
357 void Render::seek(GenTime time)
358 {
359     if (!m_mltProducer)
360         return;
361
362     m_mltProducer->seek((int)(time.frames(m_fps)));
363     if (m_mltProducer->get_speed() == 0) {
364         refresh();
365     }
366 }
367
368 void Render::seek(int time)
369 {
370     if (!m_mltProducer)
371         return;
372
373     m_mltProducer->seek(time);
374     if (m_mltProducer->get_speed() == 0) {
375         refresh();
376     }
377 }
378
379 //static
380 /*QPixmap Render::frameThumbnail(Mlt::Frame *frame, int width, int height, bool border) {
381     QPixmap pix(width, height);
382
383     mlt_image_format format = mlt_image_rgb24a;
384     uint8_t *thumb = frame->get_image(format, width, height);
385     QImage image(thumb, width, height, QImage::Format_ARGB32);
386
387     if (!image.isNull()) {
388         pix = pix.fromImage(image);
389         if (border) {
390             QPainter painter(&pix);
391             painter.drawRect(0, 0, width - 1, height - 1);
392         }
393     } else pix.fill(Qt::black);
394     return pix;
395 }
396 */
397 int Render::frameRenderWidth() const
398 {
399     return m_mltProfile->width();
400 }
401
402 int Render::renderWidth() const
403 {
404     return (int)(m_mltProfile->height() * m_mltProfile->dar() + 0.5);
405 }
406
407 int Render::renderHeight() const
408 {
409     return m_mltProfile->height();
410 }
411
412 QImage Render::extractFrame(int frame_position, QString path, int width, int height)
413 {
414     if (width == -1) {
415         width = frameRenderWidth();
416         height = renderHeight();
417     } else if (width % 2 == 1) width++;
418     int dwidth = height * frameRenderWidth() / renderHeight();
419     if (!path.isEmpty()) {
420         Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile, path.toUtf8().constData());
421         if (producer) {
422             if (producer->is_valid()) {
423                 QImage img = KThumb::getFrame(producer, frame_position, dwidth, width, height);
424                 delete producer;
425                 return img;
426             }
427             else delete producer;
428         }
429     }
430     
431     if (!m_mltProducer || !path.isEmpty()) {
432         QImage pix(width, height, QImage::Format_RGB32);
433         pix.fill(Qt::black);
434         return pix;
435     }
436     return KThumb::getFrame(m_mltProducer, frame_position, dwidth, width, height);
437 }
438
439 QPixmap Render::getImageThumbnail(KUrl url, int /*width*/, int /*height*/)
440 {
441     QImage im;
442     QPixmap pixmap;
443     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
444         QString fileType = url.fileName().right(3);
445         QStringList more;
446         QStringList::Iterator it;
447
448         QDir dir(url.directory());
449         QStringList filter;
450         filter << "*." + fileType;
451         filter << "*." + fileType.toUpper();
452         more = dir.entryList(filter, QDir::Files);
453         im.load(url.directory() + '/' + more.at(0));
454     } else im.load(url.path());
455     //pixmap = im.scaled(width, height);
456     return pixmap;
457 }
458
459 double Render::consumerRatio() const
460 {
461     if (!m_mltConsumer) return 1.0;
462     return (m_mltConsumer->get_double("aspect_ratio_num") / m_mltConsumer->get_double("aspect_ratio_den"));
463 }
464
465
466 int Render::getLength()
467 {
468
469     if (m_mltProducer) {
470         // kDebug()<<"//////  LENGTH: "<<mlt_producer_get_playtime(m_mltProducer->get_producer());
471         return mlt_producer_get_playtime(m_mltProducer->get_producer());
472     }
473     return 0;
474 }
475
476 bool Render::isValid(KUrl url)
477 {
478     Mlt::Producer producer(*m_mltProfile, url.path().toUtf8().constData());
479     if (producer.is_blank())
480         return false;
481
482     return true;
483 }
484
485 double Render::dar() const
486 {
487     return m_mltProfile->dar();
488 }
489
490 double Render::sar() const
491 {
492     return m_mltProfile->sar();
493 }
494
495 void Render::slotSplitView(bool doit)
496 {
497     m_isSplitView = doit;
498     Mlt::Service service(m_mltProducer->parent().get_service());
499     Mlt::Tractor tractor(service);
500     if (service.type() != tractor_type || tractor.count() < 2) return;
501     Mlt::Field *field = tractor.field();
502     if (doit) {
503         for (int i = 1, screen = 0; i < tractor.count() && screen < 4; i++) {
504             Mlt::Producer trackProducer(tractor.track(i));
505             kDebug() << "// TRACK: " << i << ", HIDE: " << trackProducer.get("hide");
506             if (QString(trackProducer.get("hide")).toInt() != 1) {
507                 kDebug() << "// ADIDNG TRACK: " << i;
508                 Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
509                 transition->set("mlt_service", "composite");
510                 transition->set("a_track", 0);
511                 transition->set("b_track", i);
512                 transition->set("distort", 1);
513                 transition->set("internal_added", "200");
514                 const char *tmp;
515                 switch (screen) {
516                 case 0:
517                     tmp = "0,0:50%x50%";
518                     break;
519                 case 1:
520                     tmp = "50%,0:50%x50%";
521                     break;
522                 case 2:
523                     tmp = "0,50%:50%x50%";
524                     break;
525                 case 3:
526                 default:
527                     tmp = "50%,50%:50%x50%";
528                     break;
529                 }
530                 transition->set("geometry", tmp);
531                 transition->set("always_active", "1");
532                 field->plant_transition(*transition, 0, i);
533                 //delete[] tmp;
534                 screen++;
535             }
536         }
537         m_mltConsumer->set("refresh", 1);
538     } else {
539         mlt_service serv = m_mltProducer->parent().get_service();
540         mlt_service nextservice = mlt_service_get_producer(serv);
541         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
542         QString mlt_type = mlt_properties_get(properties, "mlt_type");
543         QString resource = mlt_properties_get(properties, "mlt_service");
544
545         while (mlt_type == "transition") {
546             QString added = mlt_properties_get(MLT_SERVICE_PROPERTIES(nextservice), "internal_added");
547             if (added == "200") {
548                 mlt_field_disconnect_service(field->get_field(), nextservice);
549             }
550             nextservice = mlt_service_producer(nextservice);
551             if (nextservice == NULL) break;
552             properties = MLT_SERVICE_PROPERTIES(nextservice);
553             mlt_type = mlt_properties_get(properties, "mlt_type");
554             resource = mlt_properties_get(properties, "mlt_service");
555             m_mltConsumer->set("refresh", 1);
556         }
557     }
558 }
559
560 void Render::getFileProperties(const QDomElement &xml, const QString &clipId, int imageHeight, bool replaceProducer)
561 {
562     requestClipInfo info;
563     info.xml = xml;
564     info.clipId = clipId;
565     info.imageHeight = imageHeight;
566     info.replaceProducer = replaceProducer;
567     // Make sure we don't request the info for same clip twice
568     m_requestList.removeAll(info);
569     m_requestList.append(info);
570     if (!m_infoThread.isRunning())
571         m_infoThread = QtConcurrent::run(this, &Render::processFileProperties);
572 }
573
574 void Render::forceProcessing(const QString &id)
575 {
576     m_infoMutex.lock();
577     for (int i = 0; i < m_requestList.count(); i++) {
578         requestClipInfo info = m_requestList.at(i);
579         if (info.clipId == id) {
580             if (i == 0) break;
581             else {
582                 m_requestList.removeAt(i);
583                 m_requestList.prepend(info);
584                 break;
585             }
586         }
587     }
588     m_infoMutex.unlock();
589 }
590
591 int Render::processingItems() const
592 {
593     int count = m_requestList.count();
594     if (m_infoThread.isRunning()) count++;
595     return count;
596 }
597
598 void Render::processFileProperties()
599 {
600     requestClipInfo info;
601     QLocale locale;
602     while (!m_requestList.isEmpty()) {
603         m_infoMutex.lock();
604         info = m_requestList.takeFirst();
605         m_infoMutex.unlock();
606         if (info.replaceProducer) emit blockClipMonitor(info.clipId);
607         QString path;
608         bool proxyProducer;
609         if (info.xml.hasAttribute("proxy") && info.xml.attribute("proxy") != "-") {
610             path = info.xml.attribute("proxy");
611             proxyProducer = true;
612         }
613         else {
614             path = info.xml.attribute("resource");
615             proxyProducer = false;
616         }
617         KUrl url(path);
618         Mlt::Producer *producer = NULL;
619         CLIPTYPE type = (CLIPTYPE)info.xml.attribute("type").toInt();
620
621         if (type == COLOR) {
622             producer = new Mlt::Producer(*m_mltProfile, 0, ("colour:" + info.xml.attribute("colour")).toUtf8().constData());
623         } else if (type == TEXT) {
624             producer = new Mlt::Producer(*m_mltProfile, 0, ("kdenlivetitle:" + info.xml.attribute("resource")).toUtf8().constData());
625             if (producer && producer->is_valid() && info.xml.hasAttribute("xmldata"))
626                 producer->set("xmldata", info.xml.attribute("xmldata").toUtf8().constData());
627         } else if (url.isEmpty()) {
628             QDomDocument doc;
629             QDomElement mlt = doc.createElement("mlt");
630             QDomElement play = doc.createElement("playlist");
631             doc.appendChild(mlt);
632             mlt.appendChild(play);
633             play.appendChild(doc.importNode(info.xml, true));
634             producer = new Mlt::Producer(*m_mltProfile, "xml-string", doc.toString().toUtf8().constData());
635         } else {
636             producer = new Mlt::Producer(*m_mltProfile, path.toUtf8().constData());
637         }
638
639         if (producer == NULL || producer->is_blank() || !producer->is_valid()) {
640             kDebug() << " / / / / / / / / ERROR / / / / // CANNOT LOAD PRODUCER: "<<path;
641             if (proxyProducer) {
642                 // Proxy file is corrupted
643                 emit removeInvalidProxy(info.clipId, false);
644             }
645             else emit removeInvalidClip(info.clipId, info.replaceProducer);
646             delete producer;
647             continue;
648         }
649
650         if (proxyProducer && info.xml.hasAttribute("proxy_out")) {
651             producer->set("length", info.xml.attribute("proxy_out").toInt() + 1);
652             producer->set("out", info.xml.attribute("proxy_out").toInt());
653             if (producer->get_out() != info.xml.attribute("proxy_out").toInt()) {
654                 // Proxy file length is different than original clip length, this will corrupt project so disable this proxy clip
655                 emit removeInvalidProxy(info.clipId, true);
656                 delete producer;
657                 continue;
658             }
659         }
660
661         if (info.xml.hasAttribute("force_aspect_ratio")) {
662             double aspect = info.xml.attribute("force_aspect_ratio").toDouble();
663             if (aspect > 0) producer->set("force_aspect_ratio", aspect);
664         }
665
666         if (info.xml.hasAttribute("force_aspect_num") && info.xml.hasAttribute("force_aspect_den")) {
667             int width = info.xml.attribute("frame_size").section('x', 0, 0).toInt();
668             int height = info.xml.attribute("frame_size").section('x', 1, 1).toInt();
669             int aspectNumerator = info.xml.attribute("force_aspect_num").toInt();
670             int aspectDenominator = info.xml.attribute("force_aspect_den").toInt();
671             if (aspectDenominator != 0 && width != 0)
672                 producer->set("force_aspect_ratio", double(height) * aspectNumerator / aspectDenominator / width);
673         }
674
675         if (info.xml.hasAttribute("force_fps")) {
676             double fps = info.xml.attribute("force_fps").toDouble();
677             if (fps > 0) producer->set("force_fps", fps);
678         }
679
680         if (info.xml.hasAttribute("force_progressive")) {
681             bool ok;
682             int progressive = info.xml.attribute("force_progressive").toInt(&ok);
683             if (ok) producer->set("force_progressive", progressive);
684         }
685         if (info.xml.hasAttribute("force_tff")) {
686             bool ok;
687             int fieldOrder = info.xml.attribute("force_tff").toInt(&ok);
688             if (ok) producer->set("force_tff", fieldOrder);
689         }
690         if (info.xml.hasAttribute("threads")) {
691             int threads = info.xml.attribute("threads").toInt();
692             if (threads != 1) producer->set("threads", threads);
693         }
694         if (info.xml.hasAttribute("video_index")) {
695             int vindex = info.xml.attribute("video_index").toInt();
696             if (vindex != 0) producer->set("video_index", vindex);
697         }
698         if (info.xml.hasAttribute("audio_index")) {
699             int aindex = info.xml.attribute("audio_index").toInt();
700             if (aindex != 0) producer->set("audio_index", aindex);
701         }
702         if (info.xml.hasAttribute("force_colorspace")) {
703             int colorspace = info.xml.attribute("force_colorspace").toInt();
704             if (colorspace != 0) producer->set("force_colorspace", colorspace);
705         }
706         if (info.xml.hasAttribute("full_luma")) {
707             int full_luma = info.xml.attribute("full_luma").toInt();
708             if (full_luma != 0) producer->set("set.force_full_luma", full_luma);
709         }
710
711         int clipOut = 0;
712         int duration = 0;
713         if (info.xml.hasAttribute("out")) clipOut = info.xml.attribute("out").toInt();
714
715         // setup length here as otherwise default length (currently 15000 frames in MLT) will be taken even if outpoint is larger
716         if (type == COLOR || type == TEXT || type == IMAGE || type == SLIDESHOW) {
717             int length;
718             if (info.xml.hasAttribute("length")) {
719                 if (clipOut > 0) duration = clipOut + 1;
720                 length = info.xml.attribute("length").toInt();
721                 clipOut = length - 1;
722             }
723             else length = info.xml.attribute("out").toInt() - info.xml.attribute("in").toInt();
724             producer->set("length", length);
725         }
726
727         if (clipOut > 0) producer->set_in_and_out(info.xml.attribute("in").toInt(), clipOut);
728
729         producer->set("id", info.clipId.toUtf8().constData());
730
731         if (info.xml.hasAttribute("templatetext"))
732             producer->set("templatetext", info.xml.attribute("templatetext").toUtf8().constData());
733         
734         if ((!info.replaceProducer && info.xml.hasAttribute("file_hash")) || proxyProducer) {
735             // Clip  already has all properties
736             emit replyGetFileProperties(info.clipId, producer, stringMap(), stringMap(), info.replaceProducer, true);
737             continue;
738         }
739
740         int imageWidth = (int)((double) info.imageHeight * m_mltProfile->width() / m_mltProfile->height() + 0.5);
741         int fullWidth = (int)((double) info.imageHeight * m_mltProfile->dar() + 0.5);
742         stringMap filePropertyMap;
743         stringMap metadataPropertyMap;
744
745         int frameNumber = info.xml.attribute("thumbnail", "-1").toInt();
746         if (frameNumber > 0) producer->seek(frameNumber);
747         
748         duration = duration > 0 ? duration : producer->get_playtime();
749         filePropertyMap["duration"] = QString::number(duration);
750         //kDebug() << "///////  PRODUCER: " << url.path() << " IS: " << producer->get_playtime();
751
752         if (type == SLIDESHOW) {
753             int ttl = info.xml.hasAttribute("ttl") ? info.xml.attribute("ttl").toInt() : 0;
754             if (ttl) producer->set("ttl", ttl);
755             if (!info.xml.attribute("animation").isEmpty()) {
756                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, "affine");
757                 if (filter && filter->is_valid()) {
758                     int cycle = ttl;
759                     QString geometry = SlideshowClip::animationToGeometry(info.xml.attribute("animation"), cycle);
760                     if (!geometry.isEmpty()) {
761                         if (info.xml.attribute("animation").contains("low-pass")) {
762                             Mlt::Filter *blur = new Mlt::Filter(*m_mltProfile, "boxblur");
763                             if (blur && blur->is_valid())
764                                 producer->attach(*blur);
765                         }
766                         filter->set("transition.geometry", geometry.toUtf8().data());
767                         filter->set("transition.cycle", cycle);
768                         producer->attach(*filter);
769                     }
770                 }
771             }
772             if (info.xml.attribute("fade") == "1") {
773                 // user wants a fade effect to slideshow
774                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, "luma");
775                 if (filter && filter->is_valid()) {
776                     if (ttl) filter->set("cycle", ttl);
777                     if (info.xml.hasAttribute("luma_duration") && !info.xml.attribute("luma_duration").isEmpty()) filter->set("duration",      info.xml.attribute("luma_duration").toInt());
778                     if (info.xml.hasAttribute("luma_file") && !info.xml.attribute("luma_file").isEmpty()) {
779                         filter->set("luma.resource", info.xml.attribute("luma_file").toUtf8().constData());
780                         if (info.xml.hasAttribute("softness")) {
781                             int soft = info.xml.attribute("softness").toInt();
782                             filter->set("luma.softness", (double) soft / 100.0);
783                         }
784                     }
785                     producer->attach(*filter);
786                 }
787             }
788             if (info.xml.attribute("crop") == "1") {
789                 // user wants to center crop the slides
790                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, "crop");
791                 if (filter && filter->is_valid()) {
792                     filter->set("center", 1);
793                     producer->attach(*filter);
794                 }
795             }
796         }
797
798         if (producer->get_double("meta.media.frame_rate_den") > 0) {
799             filePropertyMap["fps"] = locale.toString(producer->get_double("meta.media.frame_rate_num") / producer->get_double("meta.media.frame_rate_den"));
800         } else filePropertyMap["fps"] = producer->get("source_fps");
801
802         Mlt::Frame *frame = producer->get_frame();
803         if (frame && frame->is_valid()) {
804             filePropertyMap["frame_size"] = QString::number(frame->get_int("width")) + 'x' + QString::number(frame->get_int("height"));
805             filePropertyMap["frequency"] = QString::number(frame->get_int("frequency"));
806             filePropertyMap["channels"] = QString::number(frame->get_int("channels"));
807             filePropertyMap["aspect_ratio"] = frame->get("aspect_ratio");
808
809             if (frame->get_int("test_image") == 0) {
810                 if (url.path().endsWith(".mlt") || url.path().endsWith(".westley") || url.path().endsWith(".kdenlive")) {
811                     filePropertyMap["type"] = "playlist";
812                     metadataPropertyMap["comment"] = QString::fromUtf8(producer->get("title"));
813                 } else if (frame->get_int("test_audio") == 0)
814                     filePropertyMap["type"] = "av";
815                 else
816                     filePropertyMap["type"] = "video";
817
818                 int variance;
819                 QImage img;
820                 do {
821                     variance = 100;
822                     img = KThumb::getFrame(frame, imageWidth, fullWidth, info.imageHeight);
823                     variance = KThumb::imageVariance(img);
824                     if (frameNumber == -1 && variance< 6) {
825                         // Thumbnail is not interesting (for example all black, seek to fetch better thumb
826                         frameNumber =  duration > 100 ? 100 : duration / 2 ;
827                         producer->seek(frameNumber);
828                         delete frame;
829                         frame = producer->get_frame();
830                         variance = -1;
831                     }
832                 } while (variance == -1);
833                 if (frameNumber > -1) filePropertyMap["thumbnail"] = frameNumber;
834                 emit replyGetImage(info.clipId, img);
835             } else if (frame->get_int("test_audio") == 0) {
836                 emit replyGetImage(info.clipId, "audio-x-generic", fullWidth, info.imageHeight);
837                 filePropertyMap["type"] = "audio";
838             }
839         }
840         delete frame;
841         // Retrieve audio / video codec name
842
843         // If there is a
844         char property[200];
845         if (producer->get_int("video_index") > -1) {
846             /*if (context->duration == AV_NOPTS_VALUE) {
847             kDebug() << " / / / / / / / /ERROR / / / CLIP HAS UNKNOWN DURATION";
848                 emit removeInvalidClip(clipId);
849             delete producer;
850             return;
851             }*/
852             // Get the video_index
853             int default_video = producer->get_int("video_index");
854             int video_max = 0;
855             int default_audio = producer->get_int("audio_index");
856             int audio_max = 0;
857
858             // Find maximum stream index values
859             for (int ix = 0; ix < producer->get_int("meta.media.nb_streams"); ix++) {
860                 snprintf(property, sizeof(property), "meta.media.%d.stream.type", ix);
861                 QString type = producer->get(property);
862                 if (type == "video")
863                     video_max = ix;
864                 else if (type == "audio")
865                     audio_max = ix;
866             }
867             filePropertyMap["default_video"] = QString::number(default_video);
868             filePropertyMap["video_max"] = QString::number(video_max);
869             filePropertyMap["default_audio"] = QString::number(default_audio);
870             filePropertyMap["audio_max"] = QString::number(audio_max);
871
872             snprintf(property, sizeof(property), "meta.media.%d.codec.long_name", default_video);
873             if (producer->get(property)) {
874                 filePropertyMap["videocodec"] = producer->get(property);
875             } else {
876                 snprintf(property, sizeof(property), "meta.media.%d.codec.name", default_video);
877                 if (producer->get(property))
878                     filePropertyMap["videocodec"] = producer->get(property);
879             }
880             QString query;
881             query = QString("meta.media.%1.codec.pix_fmt").arg(default_video);
882             filePropertyMap["pix_fmt"] = producer->get(query.toUtf8().constData());
883             filePropertyMap["colorspace"] = producer->get("meta.media.colorspace");
884
885         } else kDebug() << " / / / / /WARNING, VIDEO CONTEXT IS NULL!!!!!!!!!!!!!!";
886         if (producer->get_int("audio_index") > -1) {
887             // Get the audio_index
888             int index = producer->get_int("audio_index");
889             snprintf(property, sizeof(property), "meta.media.%d.codec.long_name", index);
890             if (producer->get(property)) {
891                 filePropertyMap["audiocodec"] = producer->get(property);
892             } else {
893                 snprintf(property, sizeof(property), "meta.media.%d.codec.name", index);
894                 if (producer->get(property))
895                     filePropertyMap["audiocodec"] = producer->get(property);
896             }
897         }
898
899         // metadata
900         Mlt::Properties metadata;
901         metadata.pass_values(*producer, "meta.attr.");
902         int count = metadata.count();
903         for (int i = 0; i < count; i ++) {
904             QString name = metadata.get_name(i);
905             QString value = QString::fromUtf8(metadata.get(i));
906             if (name.endsWith("markup") && !value.isEmpty())
907                 metadataPropertyMap[ name.section('.', 0, -2)] = value;
908         }
909         producer->seek(0);
910         emit replyGetFileProperties(info.clipId, producer, filePropertyMap, metadataPropertyMap, info.replaceProducer);
911     }
912 }
913
914
915 #if 0
916 /** Create the producer from the MLT XML QDomDocument */
917 void Render::initSceneList()
918 {
919     kDebug() << "--------  INIT SCENE LIST ------_";
920     QDomDocument doc;
921     QDomElement mlt = doc.createElement("mlt");
922     doc.appendChild(mlt);
923     QDomElement prod = doc.createElement("producer");
924     prod.setAttribute("resource", "colour");
925     prod.setAttribute("colour", "red");
926     prod.setAttribute("id", "black");
927     prod.setAttribute("in", "0");
928     prod.setAttribute("out", "0");
929
930     QDomElement tractor = doc.createElement("tractor");
931     QDomElement multitrack = doc.createElement("multitrack");
932
933     QDomElement playlist1 = doc.createElement("playlist");
934     playlist1.appendChild(prod);
935     multitrack.appendChild(playlist1);
936     QDomElement playlist2 = doc.createElement("playlist");
937     multitrack.appendChild(playlist2);
938     QDomElement playlist3 = doc.createElement("playlist");
939     multitrack.appendChild(playlist3);
940     QDomElement playlist4 = doc.createElement("playlist");
941     multitrack.appendChild(playlist4);
942     QDomElement playlist5 = doc.createElement("playlist");
943     multitrack.appendChild(playlist5);
944     tractor.appendChild(multitrack);
945     mlt.appendChild(tractor);
946     // kDebug()<<doc.toString();
947     /*
948        QString tmp = QString("<mlt><producer resource=\"colour\" colour=\"red\" id=\"red\" /><tractor><multitrack><playlist></playlist><playlist></playlist><playlist /><playlist /><playlist></playlist></multitrack></tractor></mlt>");*/
949     setSceneList(doc, 0);
950 }
951 #endif
952
953 int Render::setProducer(Mlt::Producer *producer, int position)
954 {
955     kDebug()<<"//////////\n SET CLIP PRODUCER  \n//////////";
956     QMutexLocker locker(&m_mutex);
957     if (m_winid == -1) return -1;
958     if (m_mltConsumer) {
959         if (!m_mltConsumer->is_stopped()) {
960             m_mltConsumer->stop();
961             m_mltConsumer->purge();
962         }
963         m_mltConsumer->set("refresh", 0);
964     }
965     else {
966         return -1;
967     }
968
969     if (m_mltProducer) {
970         m_mltProducer->set_speed(0);
971         delete m_mltProducer;
972         m_mltProducer = NULL;
973         emit stopped();
974     }
975     blockSignals(true);
976     if (producer && producer->is_valid()) {
977         m_mltProducer = new Mlt::Producer(producer->get_producer());
978     } else m_mltProducer = m_blackClip->cut(0, 1);
979
980     if (!m_mltProducer || !m_mltProducer->is_valid()) {
981         kDebug() << " WARNING - - - - -INVALID PLAYLIST: ";
982         return -1;
983     }
984     int volume = KdenliveSettings::volume();
985     m_mltProducer->set("meta.volume", (double)volume / 100);
986     m_fps = m_mltProducer->get_fps();
987     blockSignals(false);
988     int error = connectPlaylist();
989     if (producer == NULL) {
990         return error;
991     }
992
993     if (position != -1) {
994         m_mltProducer->seek(position);
995         emit rendererPosition(position);
996     } else emit rendererPosition((int) m_mltProducer->position());
997     return error;
998 }
999
1000 int Render::setSceneList(QDomDocument list, int position)
1001 {
1002     return setSceneList(list.toString(), position);
1003 }
1004
1005 int Render::setSceneList(QString playlist, int position)
1006 {
1007     if (m_winid == -1) return -1;
1008     int error = 0;
1009
1010     //kDebug() << "//////  RENDER, SET SCENE LIST:\n" << playlist <<"\n..........:::.";
1011
1012     // Remove previous profile info
1013     QDomDocument doc;
1014     doc.setContent(playlist);
1015     QDomElement profile = doc.documentElement().firstChildElement("profile");
1016     doc.documentElement().removeChild(profile);
1017     playlist = doc.toString();
1018
1019     if (m_mltConsumer) {
1020         if (!m_mltConsumer->is_stopped()) {
1021             m_mltConsumer->stop();
1022         }
1023         m_mltConsumer->set("refresh", 0);
1024     } else {
1025         kWarning() << "///////  ERROR, TRYING TO USE NULL MLT CONSUMER";
1026         error = -1;
1027     }
1028     m_requestList.clear();
1029     m_infoThread.waitForFinished();
1030
1031     if (m_mltProducer) {
1032         m_mltProducer->set_speed(0);
1033         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
1034
1035         /*Mlt::Service service(m_mltProducer->parent().get_service());
1036         service.lock();
1037
1038         if (service.type() == tractor_type) {
1039             Mlt::Tractor tractor(service);
1040             Mlt::Field *field = tractor.field();
1041             mlt_service nextservice = mlt_service_get_producer(service.get_service());
1042             mlt_service nextservicetodisconnect;
1043             mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1044             QString mlt_type = mlt_properties_get(properties, "mlt_type");
1045             QString resource = mlt_properties_get(properties, "mlt_service");
1046             // Delete all transitions
1047             while (mlt_type == "transition") {
1048                 nextservicetodisconnect = nextservice;
1049                 nextservice = mlt_service_producer(nextservice);
1050                 mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
1051                 if (nextservice == NULL) break;
1052                 properties = MLT_SERVICE_PROPERTIES(nextservice);
1053                 mlt_type = mlt_properties_get(properties, "mlt_type");
1054                 resource = mlt_properties_get(properties, "mlt_service");
1055             }
1056
1057
1058             for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
1059                 Mlt::Producer trackProducer(tractor.track(trackNb));
1060                 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1061                 if (trackPlaylist.type() == playlist_type) trackPlaylist.clear();
1062             }
1063             delete field;
1064         }
1065         service.unlock();*/
1066
1067         qDeleteAll(m_slowmotionProducers.values());
1068         m_slowmotionProducers.clear();
1069
1070         delete m_mltProducer;
1071         m_mltProducer = NULL;
1072         emit stopped();
1073     }
1074
1075     blockSignals(true);
1076     m_locale = QLocale();
1077
1078     m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", playlist.toUtf8().constData());
1079     if (!m_mltProducer || !m_mltProducer->is_valid()) {
1080         kDebug() << " WARNING - - - - -INVALID PLAYLIST: " << playlist.toUtf8().constData();
1081         m_mltProducer = m_blackClip->cut(0, 1);
1082         error = -1;
1083     }
1084     checkMaxThreads();
1085     int volume = KdenliveSettings::volume();
1086     m_mltProducer->set("meta.volume", (double)volume / 100);
1087     m_mltProducer->optimise();
1088
1089     /*if (KdenliveSettings::osdtimecode()) {
1090     // Attach filter for on screen display of timecode
1091     delete m_osdInfo;
1092     QString attr = "attr_check";
1093     mlt_filter filter = mlt_factory_filter( "data_feed", (char*) attr.ascii() );
1094     mlt_properties_set_int( MLT_FILTER_PROPERTIES( filter ), "_loader", 1 );
1095     mlt_producer_attach( m_mltProducer->get_producer(), filter );
1096     mlt_filter_close( filter );
1097
1098       m_osdInfo = new Mlt::Filter("data_show");
1099     m_osdInfo->set("resource", m_osdProfile.toUtf8().constData());
1100     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1101     mlt_properties_set_int( properties, "meta.attr.timecode", 1);
1102     mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
1103     m_osdInfo->set("dynamic", "1");
1104
1105       if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
1106     } else {
1107     m_osdInfo->set("dynamic", "0");
1108     }*/
1109
1110     m_fps = m_mltProducer->get_fps();
1111     if (position != 0) {
1112         // Seek to correct place after opening project.
1113         m_mltProducer->seek(position);
1114     }
1115
1116     kDebug() << "// NEW SCENE LIST DURATION SET TO: " << m_mltProducer->get_playtime();
1117     if (error == 0) error = connectPlaylist();
1118     else connectPlaylist();
1119     fillSlowMotionProducers();
1120     blockSignals(false);
1121
1122     return error;
1123     //kDebug()<<"// SETSCN LST, POS: "<<position;
1124     //if (position != 0) emit rendererPosition(position);
1125 }
1126
1127 void Render::checkMaxThreads()
1128 {
1129     // Make sure we don't use too much threads, MLT avformat does not cope with too much threads
1130     // Currently, Kdenlive uses the following avformat threads:
1131     // One thread to get info when adding a clip
1132     // One thread to create the timeline video thumbnails
1133     // One thread to create the audio thumbnails
1134     Mlt::Service service(m_mltProducer->parent().get_service());
1135     if (service.type() != tractor_type) {
1136         kWarning() << "// TRACTOR PROBLEM";
1137         return;
1138     }
1139     Mlt::Tractor tractor(service);
1140     int mltMaxThreads = mlt_service_cache_get_size(service.get_service(), "producer_avformat");
1141     int requestedThreads = tractor.count() + 4;
1142     if (requestedThreads > mltMaxThreads) {
1143         mlt_service_cache_set_size(service.get_service(), "producer_avformat", requestedThreads);
1144         kDebug()<<"// MLT threads updated to: "<<mlt_service_cache_get_size(service.get_service(), "producer_avformat");
1145     }
1146 }
1147
1148 const QString Render::sceneList()
1149 {
1150     QString playlist;
1151     Mlt::Profile profile((mlt_profile) 0);
1152     Mlt::Consumer xmlConsumer(profile, "xml:kdenlive_playlist");
1153     m_mltProducer->optimise();
1154     xmlConsumer.set("terminate_on_pause", 1);
1155     Mlt::Producer prod(m_mltProducer->get_producer());
1156     bool split = m_isSplitView;
1157     if (split) slotSplitView(false);
1158     xmlConsumer.connect(prod);
1159     xmlConsumer.start();
1160     while (!xmlConsumer.is_stopped()) {}
1161     playlist = QString::fromUtf8(xmlConsumer.get("kdenlive_playlist"));
1162     if (split) slotSplitView(true);
1163     return playlist;
1164 }
1165
1166 bool Render::saveSceneList(QString path, QDomElement kdenliveData)
1167 {
1168     QFile file(path);
1169     QDomDocument doc;
1170     doc.setContent(sceneList(), false);
1171     if (!kdenliveData.isNull()) {
1172         // add Kdenlive specific tags
1173         QDomNode mlt = doc.elementsByTagName("mlt").at(0);
1174         mlt.appendChild(doc.importNode(kdenliveData, true));
1175     }
1176     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1177         kWarning() << "//////  ERROR writing to file: " << path;
1178         return false;
1179     }
1180     file.write(doc.toString().toUtf8());
1181     if (file.error() != QFile::NoError) {
1182         file.close();
1183         return false;
1184     }
1185     file.close();
1186     return true;
1187 }
1188
1189 void Render::saveZone(KUrl url, QString desc, QPoint zone)
1190 {
1191     Mlt::Consumer xmlConsumer(*m_mltProfile, ("xml:" + url.path()).toUtf8().constData());
1192     m_mltProducer->optimise();
1193     xmlConsumer.set("terminate_on_pause", 1);
1194     if (m_name == "clip") {
1195         Mlt::Producer *prod = m_mltProducer->cut(zone.x(), zone.y());
1196         Mlt::Playlist list;
1197         list.insert_at(0, prod, 0);
1198         delete prod;
1199         list.set("title", desc.toUtf8().constData());
1200         xmlConsumer.connect(list);
1201
1202     } else {
1203         //TODO: not working yet, save zone from timeline
1204         Mlt::Producer *p1 = new Mlt::Producer(m_mltProducer->get_producer());
1205         /* Mlt::Service service(p1->parent().get_service());
1206          if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";*/
1207
1208         //Mlt::Producer *prod = p1->cut(zone.x(), zone.y());
1209         //prod->set("title", desc.toUtf8().constData());
1210         xmlConsumer.connect(*p1); //list);
1211     }
1212
1213     xmlConsumer.start();
1214 }
1215
1216 double Render::fps() const
1217 {
1218     return m_fps;
1219 }
1220
1221 int Render::connectPlaylist()
1222 {
1223     if (!m_mltConsumer) return -1;
1224     //m_mltConsumer->set("refresh", "0");
1225     m_mltConsumer->connect(*m_mltProducer);
1226     m_mltProducer->set_speed(0);
1227     if (m_mltConsumer->start() == -1) {
1228         // ARGH CONSUMER BROKEN!!!!
1229         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."));
1230         delete m_mltConsumer;
1231         m_mltConsumer = NULL;
1232         return -1;
1233     }
1234     emit durationChanged(m_mltProducer->get_playtime());
1235     return 0;
1236     //refresh();
1237 }
1238
1239
1240 int Render::volume() const
1241 {
1242     if (!m_mltConsumer || !m_mltProducer) return -1;
1243     return ((int) 100 * m_mltProducer->get_double("meta.volume"));
1244 }
1245
1246 void Render::slotSetVolume(int volume)
1247 {
1248     if (!m_mltConsumer || !m_mltProducer) return;
1249     m_mltProducer->set("meta.volume", (double)volume / 100.0);
1250     return;
1251     /*osdTimer->stop();
1252     m_mltConsumer->set("refresh", 0);
1253     // Attach filter for on screen display of timecode
1254     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1255     mlt_properties_set_double( properties, "meta.volume", volume );
1256     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
1257     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
1258
1259     if (!KdenliveSettings::osdtimecode()) {
1260     m_mltProducer->detach(*m_osdInfo);
1261     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
1262      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
1263     }*/
1264     refresh();
1265     //m_osdTimer->setSingleShot(2500);
1266 }
1267
1268 void Render::slotOsdTimeout()
1269 {
1270     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1271     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
1272     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
1273     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
1274     refresh();
1275 }
1276
1277 void Render::start()
1278 {
1279     if (m_winid == -1) {
1280         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
1281         return;
1282     }
1283     if (m_mltConsumer && m_mltConsumer->is_stopped()) {
1284         if (m_mltConsumer->start() == -1) {
1285             //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."));
1286             kDebug(QtWarningMsg) << "/ / / / CANNOT START MONITOR";
1287         } else {
1288             refresh();
1289         }
1290     }
1291 }
1292
1293 void Render::stop()
1294 {
1295     if (m_mltProducer == NULL) return;
1296     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
1297         m_mltConsumer->stop();
1298     }
1299
1300     if (m_mltProducer) {
1301         if (m_isZoneMode) resetZoneMode();
1302         m_mltProducer->set_speed(0.0);
1303     }
1304 }
1305
1306 void Render::stop(const GenTime & startTime)
1307 {
1308     if (m_mltProducer) {
1309         if (m_isZoneMode) resetZoneMode();
1310         m_mltProducer->set_speed(0.0);
1311         m_mltProducer->seek((int) startTime.frames(m_fps));
1312     }
1313     m_mltConsumer->purge();
1314 }
1315
1316 void Render::pause()
1317 {
1318     if (!m_mltProducer || !m_mltConsumer)
1319         return;
1320     if (m_mltProducer->get_speed() == 0.0) return;
1321     if (m_isZoneMode) resetZoneMode();
1322     m_mltConsumer->set("refresh", 0);
1323     m_mltProducer->set_speed(0.0);
1324     m_mltConsumer->purge();
1325 }
1326
1327 void Render::switchPlay(bool play)
1328 {
1329     if (!m_mltProducer || !m_mltConsumer)
1330         return;
1331     if (m_isZoneMode) resetZoneMode();
1332     if (play && m_mltProducer->get_speed() == 0.0) {
1333         if (m_name == "clip" && m_mltConsumer->position() == m_mltProducer->get_out()) m_mltProducer->seek(0);
1334         if (m_mltConsumer->is_stopped()) {
1335             m_mltConsumer->start();
1336         }
1337         m_mltConsumer->set("refresh", "1");
1338         m_mltProducer->set_speed(1.0);
1339     } else if (!play) {
1340         m_mltConsumer->set("refresh", 0);
1341         stop();
1342         m_mltProducer->seek(m_mltConsumer->position());
1343         //emitConsumerStopped();
1344         /*m_mltConsumer->set("refresh", 0);
1345         m_mltConsumer->stop();
1346         m_mltConsumer->purge();
1347         m_mltProducer->set_speed(0.0);
1348         //m_framePosition = m_mltProducer->position();
1349         m_mltProducer->seek(m_framePosition);
1350         emit rendererPosition(m_framePosition);*/
1351     }
1352 }
1353
1354 void Render::play(double speed)
1355 {
1356     if (!m_mltProducer)
1357         return;
1358     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1359     m_mltProducer->set_speed(speed);
1360     /*if (speed == 0.0) {
1361     m_mltProducer->seek((int) m_framePosition + 1);
1362         m_mltConsumer->purge();
1363     }*/
1364     refresh();
1365 }
1366
1367 void Render::play(const GenTime & startTime)
1368 {
1369     if (!m_mltProducer || !m_mltConsumer)
1370         return;
1371     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1372     m_mltProducer->set_speed(1.0);
1373     m_mltConsumer->set("refresh", 1);
1374 }
1375
1376 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime)
1377 {
1378     if (!m_mltProducer || !m_mltConsumer)
1379         return;
1380     //m_mltProducer->set("eof", "loop");
1381     m_isLoopMode = true;
1382     m_loopStart = startTime;
1383     playZone(startTime, stopTime);
1384 }
1385
1386 void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
1387 {
1388     if (!m_mltProducer || !m_mltConsumer)
1389         return;
1390     if (!m_isZoneMode) m_originalOut = m_mltProducer->get_playtime() - 1;
1391     m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
1392     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1393     m_mltProducer->set_speed(1.0);
1394     m_mltConsumer->set("refresh", 1);
1395     m_isZoneMode = true;
1396 }
1397
1398 void Render::resetZoneMode()
1399 {
1400     if (!m_isZoneMode && !m_isLoopMode) return;
1401     m_mltProducer->set("out", m_originalOut);
1402     //m_mltProducer->set("eof", "pause");
1403     m_isZoneMode = false;
1404     m_isLoopMode = false;
1405 }
1406
1407 void Render::seekToFrame(int pos)
1408 {
1409     if (!m_mltProducer)
1410         return;
1411     
1412     resetZoneMode();
1413     m_mltProducer->seek(pos);
1414     if (m_mltProducer->get_speed() == 0) {
1415         refresh();
1416     }
1417 }
1418
1419 void Render::seekToFrameDiff(int diff)
1420 {
1421     if (!m_mltProducer)
1422         return;
1423     resetZoneMode();
1424     m_mltProducer->seek(m_mltProducer->position() + diff);
1425     refresh();
1426 }
1427
1428 void Render::doRefresh()
1429 {
1430     // Use a Timer so that we don't refresh too much
1431     if (m_mltConsumer) {
1432         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1433         m_mltConsumer->set("refresh", 1);
1434     }
1435 }
1436
1437 void Render::refresh()
1438 {
1439     if (!m_mltProducer)
1440         return;
1441     if (m_mltConsumer) {
1442         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1443         m_mltConsumer->purge();
1444         m_mltConsumer->set("refresh", 1);
1445     }
1446 }
1447
1448 void Render::setDropFrames(bool show)
1449 {
1450     if (m_mltConsumer) {
1451         int dropFrames = KdenliveSettings::mltthreads();
1452         if (show == false) dropFrames = -dropFrames;
1453         m_mltConsumer->stop();
1454         if (m_winid == 0)
1455             m_mltConsumer->set("real_time", dropFrames);
1456         else
1457             m_mltConsumer->set("play.real_time", dropFrames);
1458
1459         if (m_mltConsumer->start() == -1) {
1460             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1461         }
1462
1463     }
1464 }
1465
1466 double Render::playSpeed()
1467 {
1468     if (m_mltProducer) return m_mltProducer->get_speed();
1469     return 0.0;
1470 }
1471
1472 GenTime Render::seekPosition() const
1473 {
1474     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1475     else return GenTime();
1476 }
1477
1478 int Render::seekFramePosition() const
1479 {
1480     if (m_mltProducer) return (int) m_mltProducer->position();
1481     return 0;
1482 }
1483
1484 const QString & Render::rendererName() const
1485 {
1486     return m_name;
1487 }
1488
1489 void Render::emitFrameUpdated(Mlt::Frame& frame)
1490 {
1491     mlt_image_format format = mlt_image_rgb24;
1492     int width = 0;
1493     int height = 0;
1494     const uchar* image = frame.get_image(format, width, height);
1495     QImage qimage(width, height, QImage::Format_RGB888);
1496     memcpy(qimage.bits(), image, width * height * 3);
1497     emit frameUpdated(qimage);
1498 }
1499
1500 void Render::emitFrameNumber()
1501 {
1502     if (m_mltConsumer) emit rendererPosition((int) m_mltConsumer->position());
1503 }
1504
1505 void Render::emitConsumerStopped()
1506 {
1507     // This is used to know when the playing stopped
1508     if (m_mltProducer) {
1509         double pos = m_mltProducer->position();
1510         if (m_isLoopMode) play(m_loopStart);
1511         else if (m_isZoneMode) resetZoneMode();
1512         emit rendererStopped((int) pos);
1513     }
1514 }
1515
1516 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1517 {
1518     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1519 }
1520
1521 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
1522 {
1523     if (!m_mltProducer) {
1524         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1525         return;
1526     }
1527
1528     //int height = 1080;//KdenliveSettings::defaultheight();
1529     //int width = 1940; //KdenliveSettings::displaywidth();
1530     //TODO: rewrite
1531     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1532     /*
1533        QPixmap pix(width, height);
1534        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1535        m_convert.set("forced", mlt_image_rgb24a);
1536        m_mltProducer->attach(m_convert);
1537        Mlt::Frame * frame = m_mltProducer->get_frame();
1538        m_mltProducer->detach(m_convert);
1539        if (frame) {
1540            pix = frameThumbnail(frame, width, height);
1541            delete frame;
1542        }*/
1543     pix.save(url.path(), "PNG");
1544     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1545 }
1546
1547
1548 void Render::showFrame(Mlt::Frame& frame)
1549 {
1550     emit rendererPosition((int) m_mltConsumer->position());
1551     mlt_image_format format = mlt_image_rgb24a;
1552     int width = 0;
1553     int height = 0;
1554     const uchar* image = frame.get_image(format, width, height);
1555     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1556     memcpy(qimage.scanLine(0), image, width * height * 4);
1557     emit showImageSignal(qimage);
1558     if (analyseAudio) showAudio(frame);
1559     if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
1560         emit frameUpdated(qimage.rgbSwapped());
1561     }
1562 }
1563
1564 void Render::showAudio(Mlt::Frame& frame)
1565 {
1566     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1567         return;
1568     }
1569     mlt_audio_format audio_format = mlt_audio_s16;
1570     int freq = 0;
1571     int num_channels = 0;
1572     int samples = 0;
1573     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1574
1575     if (!data) {
1576         return;
1577     }
1578
1579     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1580     // So the vector is of size samples*channels.
1581     QVector<int16_t> sampleVector(samples*num_channels);
1582     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1583
1584     if (samples > 0) {
1585         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1586     }
1587 }
1588
1589 /*
1590  * MLT playlist direct manipulation.
1591  */
1592
1593 void Render::mltCheckLength(Mlt::Tractor *tractor)
1594 {
1595     //kDebug()<<"checking track length: "<<track<<"..........";
1596
1597     int trackNb = tractor->count();
1598     int duration = 0;
1599     int trackDuration;
1600     if (trackNb == 1) {
1601         Mlt::Producer trackProducer(tractor->track(0));
1602         duration = trackProducer.get_playtime() - 1;
1603         m_mltProducer->set("out", duration);
1604         emit durationChanged(duration);
1605         return;
1606     }
1607     while (trackNb > 1) {
1608         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1609         trackDuration = trackProducer.get_playtime() - 1;
1610         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1611         if (trackDuration > duration) duration = trackDuration;
1612         trackNb--;
1613     }
1614
1615     Mlt::Producer blackTrackProducer(tractor->track(0));
1616
1617     if (blackTrackProducer.get_playtime() - 1 != duration) {
1618         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1619         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1620         if (blackclip && blackclip->is_blank()) {
1621             delete blackclip;
1622             blackclip = NULL;
1623         }
1624
1625         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
1626             if (blackclip) delete blackclip;
1627             blackTrackPlaylist.clear();
1628             m_blackClip->set("length", duration + 1);
1629             m_blackClip->set("out", duration);
1630             blackclip = m_blackClip->cut(0, duration);
1631             blackTrackPlaylist.insert_at(0, blackclip, 1);
1632         } else {
1633             if (duration > blackclip->parent().get_length()) {
1634                 blackclip->parent().set("length", duration + 1);
1635                 blackclip->parent().set("out", duration);
1636                 blackclip->set("length", duration + 1);
1637             }
1638             blackTrackPlaylist.resize_clip(0, 0, duration);
1639         }
1640
1641         delete blackclip;
1642         m_mltProducer->set("out", duration);
1643         emit durationChanged(duration);
1644     }
1645 }
1646
1647 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
1648 {
1649     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
1650     QLocale locale;
1651     // We want a slowmotion producer
1652     double speed = element.attribute("speed", "1.0").toDouble();
1653     int strobe = element.attribute("strobe", "1").toInt();
1654     QString url = QString::fromUtf8(prod->get("resource"));
1655     url.append('?' + locale.toString(speed));
1656     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
1657     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1658     if (!slowprod || slowprod->get_producer() == NULL) {
1659         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
1660         if (strobe > 1) slowprod->set("strobe", strobe);
1661         QString id = prod->parent().get("id");
1662         if (id.contains('_')) id = id.section('_', 0, 0);
1663         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
1664         if (strobe > 1) producerid.append(':' + QString::number(strobe));
1665         slowprod->set("id", producerid.toUtf8().constData());
1666         m_slowmotionProducers.insert(url, slowprod);
1667     }
1668     return slowprod;
1669 }
1670
1671 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
1672 {
1673     if (m_mltProducer == NULL) {
1674         kDebug() << "PLAYLIST NOT INITIALISED //////";
1675         return -1;
1676     }
1677     if (prod == NULL) {
1678         kDebug() << "Cannot insert clip without producer //////";
1679         return -1;
1680     }
1681     Mlt::Producer parentProd(m_mltProducer->parent());
1682     if (parentProd.get_producer() == NULL) {
1683         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1684         return -1;
1685     }
1686
1687     Mlt::Service service(parentProd.get_service());
1688     if (service.type() != tractor_type) {
1689         kWarning() << "// TRACTOR PROBLEM";
1690         return -1;
1691     }
1692     Mlt::Tractor tractor(service);
1693     if (info.track > tractor.count() - 1) {
1694         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
1695         return -1;
1696     }
1697     service.lock();
1698     Mlt::Producer trackProducer(tractor.track(info.track));
1699     int trackDuration = trackProducer.get_playtime() - 1;
1700     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1701     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
1702     prod = checkSlowMotionProducer(prod, element);
1703     if (prod == NULL || !prod->is_valid()) {
1704         service.unlock();
1705         return -1;
1706     }
1707
1708     int cutPos = (int) info.cropStart.frames(m_fps);
1709     if (cutPos < 0) cutPos = 0;
1710     int insertPos = (int) info.startPos.frames(m_fps);
1711     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
1712     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
1713     if (overwrite && (insertPos < trackDuration)) {
1714         // Replace zone with blanks
1715         //trackPlaylist.split_at(insertPos, true);
1716         trackPlaylist.remove_region(insertPos, cutDuration + 1);
1717         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1718         trackPlaylist.insert_blank(clipIndex, cutDuration);
1719     } else if (push) {
1720         trackPlaylist.split_at(insertPos, true);
1721         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1722         trackPlaylist.insert_blank(clipIndex, cutDuration);
1723     }
1724     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
1725     delete clip;
1726     /*if (QString(prod->get("transparency")).toInt() == 1)
1727         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
1728
1729     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
1730     service.unlock();
1731     /*tractor.multitrack()->refresh();
1732     tractor.refresh();*/
1733     return 0;
1734 }
1735
1736
1737 void Render::mltCutClip(int track, GenTime position)
1738 {
1739     Mlt::Service service(m_mltProducer->parent().get_service());
1740     if (service.type() != tractor_type) {
1741         kWarning() << "// TRACTOR PROBLEM";
1742         return;
1743     }
1744
1745     Mlt::Tractor tractor(service);
1746     Mlt::Producer trackProducer(tractor.track(track));
1747     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1748
1749
1750     /* // Display playlist info
1751     kDebug()<<"////////////  BEFORE";
1752     for (int i = 0; i < trackPlaylist.count(); i++) {
1753     int blankStart = trackPlaylist.clip_start(i);
1754     int blankDuration = trackPlaylist.clip_length(i) - 1;
1755     QString blk;
1756     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1757     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1758     }*/
1759
1760     int cutPos = (int) position.frames(m_fps);
1761
1762     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
1763     if (trackPlaylist.is_blank(clipIndex)) {
1764         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
1765         return;
1766     }
1767     service.lock();
1768     int clipStart = trackPlaylist.clip_start(clipIndex);
1769     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
1770     service.unlock();
1771
1772     // duplicate effects
1773     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
1774     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
1775
1776     if (original == NULL || clip == NULL) {
1777         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
1778     }
1779     Mlt::Service clipService(original->get_service());
1780     Mlt::Service dupService(clip->get_service());
1781     delete original;
1782     delete clip;
1783     int ct = 0;
1784     Mlt::Filter *filter = clipService.filter(ct);
1785     while (filter) {
1786         // Only duplicate Kdenlive filters, and skip the fade in effects
1787         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
1788             // looks like there is no easy way to duplicate a filter,
1789             // so we will create a new one and duplicate its properties
1790             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
1791             if (dup && dup->is_valid()) {
1792                 Mlt::Properties entries(filter->get_properties());
1793                 for (int i = 0; i < entries.count(); i++) {
1794                     dup->set(entries.get_name(i), entries.get(i));
1795                 }
1796                 dupService.attach(*dup);
1797             }
1798         }
1799         ct++;
1800         filter = clipService.filter(ct);
1801     }
1802
1803     /* // Display playlist info
1804     kDebug()<<"////////////  AFTER";
1805     for (int i = 0; i < trackPlaylist.count(); i++) {
1806     int blankStart = trackPlaylist.clip_start(i);
1807     int blankDuration = trackPlaylist.clip_length(i) - 1;
1808     QString blk;
1809     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1810     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1811     }*/
1812
1813 }
1814
1815 Mlt::Tractor *Render::lockService()
1816 {
1817     if (!m_mltProducer) return NULL;
1818     Mlt::Service service(m_mltProducer->parent().get_service());
1819     if (service.type() != tractor_type) {
1820         kWarning() << "// TRACTOR PROBLEM";
1821         return NULL;
1822     }
1823     service.lock();
1824     return new Mlt::Tractor(service);
1825     
1826 }
1827
1828 void Render::unlockService(Mlt::Tractor *tractor)
1829 {
1830     if (tractor) delete tractor;
1831     if (!m_mltProducer) return;
1832     Mlt::Service service(m_mltProducer->parent().get_service());
1833     if (service.type() != tractor_type) {
1834         kWarning() << "// TRACTOR PROBLEM";
1835         return;
1836     }
1837     service.unlock();
1838 }
1839
1840 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
1841 {
1842     // TODO: optimize
1843     if (prod == NULL || tractor == NULL) {
1844         kDebug() << "Cannot update clip with null producer //////";
1845         return false;
1846     }
1847
1848     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
1849     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1850     int startPos = info.startPos.frames(m_fps);
1851     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
1852     if (trackPlaylist.is_blank(clipIndex)) {
1853         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
1854         return false;
1855     }
1856     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
1857     // keep effects
1858     QList <Mlt::Filter *> filtersList;
1859     Mlt::Service sourceService(clip->get_service());
1860     int ct = 0;
1861     Mlt::Filter *filter = sourceService.filter(ct);
1862     while (filter) {
1863         if (filter->get_int("kdenlive_ix") != 0) {
1864             filtersList.append(filter);
1865         }
1866         ct++;
1867         filter = sourceService.filter(ct);
1868     }
1869     delete clip;
1870     clip = trackPlaylist.replace_with_blank(clipIndex);
1871     delete clip;
1872     prod = checkSlowMotionProducer(prod, element);
1873     if (prod == NULL || !prod->is_valid()) {
1874         return false;
1875     }
1876
1877     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
1878     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
1879     Mlt::Service destService(clip2->get_service());
1880     delete clip2;
1881
1882     if (!filtersList.isEmpty()) {
1883         for (int i = 0; i < filtersList.count(); i++)
1884             destService.attach(*(filtersList.at(i)));
1885     }
1886     return true;
1887 }
1888
1889
1890 bool Render::mltRemoveClip(int track, GenTime position)
1891 {
1892     Mlt::Service service(m_mltProducer->parent().get_service());
1893     if (service.type() != tractor_type) {
1894         kWarning() << "// TRACTOR PROBLEM";
1895         return false;
1896     }
1897     //service.lock();
1898     Mlt::Tractor tractor(service);
1899     Mlt::Producer trackProducer(tractor.track(track));
1900     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1901     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
1902
1903     if (trackPlaylist.is_blank(clipIndex)) {
1904         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
1905         //service.unlock();
1906         return false;
1907     }
1908     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
1909     if (clip) delete clip;
1910     trackPlaylist.consolidate_blanks(0);
1911
1912     /* // Display playlist info
1913     kDebug()<<"////  AFTER";
1914     for (int i = 0; i < trackPlaylist.count(); i++) {
1915     int blankStart = trackPlaylist.clip_start(i);
1916     int blankDuration = trackPlaylist.clip_length(i) - 1;
1917     QString blk;
1918     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1919     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1920     }*/
1921     //service.unlock();
1922     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
1923     return true;
1924 }
1925
1926 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
1927 {
1928     if (!m_mltProducer) {
1929         kDebug() << "PLAYLIST NOT INITIALISED //////";
1930         return 0;
1931     }
1932     Mlt::Producer parentProd(m_mltProducer->parent());
1933     if (parentProd.get_producer() == NULL) {
1934         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1935         return 0;
1936     }
1937
1938     Mlt::Service service(parentProd.get_service());
1939     Mlt::Tractor tractor(service);
1940     int insertPos = pos.frames(m_fps);
1941
1942     Mlt::Producer trackProducer(tractor.track(track));
1943     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1944     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1945     if (clipIndex == trackPlaylist.count()) {
1946         // We are after the end of the playlist
1947         return -1;
1948     }
1949     if (!trackPlaylist.is_blank(clipIndex)) return 0;
1950     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
1951     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
1952 }
1953
1954 int Render::mltTrackDuration(int track)
1955 {
1956     if (!m_mltProducer) {
1957         kDebug() << "PLAYLIST NOT INITIALISED //////";
1958         return -1;
1959     }
1960     Mlt::Producer parentProd(m_mltProducer->parent());
1961     if (parentProd.get_producer() == NULL) {
1962         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1963         return -1;
1964     }
1965
1966     Mlt::Service service(parentProd.get_service());
1967     Mlt::Tractor tractor(service);
1968
1969     Mlt::Producer trackProducer(tractor.track(track));
1970     return trackProducer.get_playtime() - 1;
1971 }
1972
1973 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
1974 {
1975     if (!m_mltProducer) {
1976         kDebug() << "PLAYLIST NOT INITIALISED //////";
1977         return;
1978     }
1979     Mlt::Producer parentProd(m_mltProducer->parent());
1980     if (parentProd.get_producer() == NULL) {
1981         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1982         return;
1983     }
1984     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
1985     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
1986
1987     Mlt::Service service(parentProd.get_service());
1988     Mlt::Tractor tractor(service);
1989     service.lock();
1990     int diff = duration.frames(m_fps);
1991     int offset = timeOffset.frames(m_fps);
1992     int insertPos;
1993
1994     if (track != -1) {
1995         // insert space in one track only
1996         Mlt::Producer trackProducer(tractor.track(track));
1997         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1998         insertPos = trackClipStartList.value(track);
1999         if (insertPos != -1) {
2000             insertPos += offset;
2001             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2002             if (diff > 0) {
2003                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2004             } else {
2005                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2006                 if (!trackPlaylist.is_blank(clipIndex)) {
2007                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2008                 }
2009                 int position = trackPlaylist.clip_start(clipIndex);
2010                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2011                 if (blankDuration + diff == 0) {
2012                     trackPlaylist.remove(clipIndex);
2013                 } else trackPlaylist.remove_region(position, -diff);
2014             }
2015             trackPlaylist.consolidate_blanks(0);
2016         }
2017         // now move transitions
2018         mlt_service serv = m_mltProducer->parent().get_service();
2019         mlt_service nextservice = mlt_service_get_producer(serv);
2020         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2021         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2022         QString resource = mlt_properties_get(properties, "mlt_service");
2023
2024         while (mlt_type == "transition") {
2025             mlt_transition tr = (mlt_transition) nextservice;
2026             int currentTrack = mlt_transition_get_b_track(tr);
2027             int currentIn = (int) mlt_transition_get_in(tr);
2028             int currentOut = (int) mlt_transition_get_out(tr);
2029             insertPos = trackTransitionStartList.value(track);
2030             if (insertPos != -1) {
2031                 insertPos += offset;
2032                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2033                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2034                 }
2035             }
2036             nextservice = mlt_service_producer(nextservice);
2037             if (nextservice == NULL) break;
2038             properties = MLT_SERVICE_PROPERTIES(nextservice);
2039             mlt_type = mlt_properties_get(properties, "mlt_type");
2040             resource = mlt_properties_get(properties, "mlt_service");
2041         }
2042     } else {
2043         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2044             Mlt::Producer trackProducer(tractor.track(trackNb));
2045             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2046
2047             //int clipNb = trackPlaylist.count();
2048             insertPos = trackClipStartList.value(trackNb);
2049             if (insertPos != -1) {
2050                 insertPos += offset;
2051
2052                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2053                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2054                         for (int i = 0; i < clipNb; i++) {
2055                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2056                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2057                      kDebug()<<"-------------";
2058                  }
2059                  kDebug()<<"END-------------";*/
2060
2061
2062                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2063                 if (diff > 0) {
2064                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2065                 } else {
2066                     if (!trackPlaylist.is_blank(clipIndex)) {
2067                         clipIndex --;
2068                     }
2069                     if (!trackPlaylist.is_blank(clipIndex)) {
2070                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2071                     }
2072                     int position = trackPlaylist.clip_start(clipIndex);
2073                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2074                     if (diff + blankDuration == 0) {
2075                         trackPlaylist.remove(clipIndex);
2076                     } else trackPlaylist.remove_region(position, - diff);
2077                 }
2078                 trackPlaylist.consolidate_blanks(0);
2079             }
2080         }
2081         // now move transitions
2082         mlt_service serv = m_mltProducer->parent().get_service();
2083         mlt_service nextservice = mlt_service_get_producer(serv);
2084         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2085         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2086         QString resource = mlt_properties_get(properties, "mlt_service");
2087
2088         while (mlt_type == "transition") {
2089             mlt_transition tr = (mlt_transition) nextservice;
2090             int currentIn = (int) mlt_transition_get_in(tr);
2091             int currentOut = (int) mlt_transition_get_out(tr);
2092             int currentTrack = mlt_transition_get_b_track(tr);
2093             insertPos = trackTransitionStartList.value(currentTrack);
2094             if (insertPos != -1) {
2095                 insertPos += offset;
2096                 if (currentOut > insertPos && resource != "mix") {
2097                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2098                 }
2099             }
2100             nextservice = mlt_service_producer(nextservice);
2101             if (nextservice == NULL) break;
2102             properties = MLT_SERVICE_PROPERTIES(nextservice);
2103             mlt_type = mlt_properties_get(properties, "mlt_type");
2104             resource = mlt_properties_get(properties, "mlt_service");
2105         }
2106     }
2107     service.unlock();
2108     mltCheckLength(&tractor);
2109     m_mltConsumer->set("refresh", 1);
2110 }
2111
2112
2113 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2114 {
2115     if (source == dest) return;
2116     Mlt::Service sourceService(source->get_service());
2117     Mlt::Service destService(dest->get_service());
2118
2119     // move all effects to the correct producer
2120     int ct = 0;
2121     Mlt::Filter *filter = sourceService.filter(ct);
2122     while (filter) {
2123         if (filter->get_int("kdenlive_ix") != 0) {
2124             sourceService.detach(*filter);
2125             destService.attach(*filter);
2126         } else ct++;
2127         filter = sourceService.filter(ct);
2128     }
2129 }
2130
2131 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2132 {
2133     int newLength = 0;
2134     Mlt::Service service(m_mltProducer->parent().get_service());
2135     if (service.type() != tractor_type) {
2136         kWarning() << "// TRACTOR PROBLEM";
2137         return -1;
2138     }
2139
2140     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2141     Mlt::Tractor tractor(service);
2142     Mlt::Producer trackProducer(tractor.track(info.track));
2143     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2144     int startPos = info.startPos.frames(m_fps);
2145     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2146     int clipLength = trackPlaylist.clip_length(clipIndex);
2147
2148     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2149     if (original == NULL) {
2150         return -1;
2151     }
2152     if (!original->is_valid() || original->is_blank()) {
2153         // invalid clip
2154         delete original;
2155         return -1;
2156     }
2157     Mlt::Producer clipparent = original->parent();
2158     if (!clipparent.is_valid() || clipparent.is_blank()) {
2159         // invalid clip
2160         delete original;
2161         return -1;
2162     }
2163
2164     QString serv = clipparent.get("mlt_service");
2165     QString id = clipparent.get("id");
2166     if (speed <= 0 && speed > -1) speed = 1.0;
2167     //kDebug() << "CLIP SERVICE: " << serv;
2168     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2169         service.lock();
2170         QString url = QString::fromUtf8(clipparent.get("resource"));
2171         url.append('?' + m_locale.toString(speed));
2172         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2173         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2174         if (!slowprod || slowprod->get_producer() == NULL) {
2175             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2176             if (strobe > 1) slowprod->set("strobe", strobe);
2177             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2178             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2179             slowprod->set("id", producerid.toUtf8().constData());
2180             // copy producer props
2181             double ar = original->parent().get_double("force_aspect_ratio");
2182             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2183             double fps = original->parent().get_double("force_fps");
2184             if (fps != 0.0) slowprod->set("force_fps", fps);
2185             int threads = original->parent().get_int("threads");
2186             if (threads != 0) slowprod->set("threads", threads);
2187             if (original->parent().get("force_progressive"))
2188                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2189             if (original->parent().get("force_tff"))
2190                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2191             int ix = original->parent().get_int("video_index");
2192             if (ix != 0) slowprod->set("video_index", ix);
2193             int colorspace = original->parent().get_int("force_colorspace");
2194             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2195             int full_luma = original->parent().get_int("set.force_full_luma");
2196             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2197             m_slowmotionProducers.insert(url, slowprod);
2198         }
2199         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2200         trackPlaylist.consolidate_blanks(0);
2201
2202         // Check that the blank space is long enough for our new duration
2203         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2204         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2205         Mlt::Producer *cut;
2206         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2207             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2208             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2209         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2210
2211         // move all effects to the correct producer
2212         mltPasteEffects(clip, cut);
2213         trackPlaylist.insert_at(startPos, cut, 1);
2214         delete cut;
2215         delete clip;
2216         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2217         newLength = trackPlaylist.clip_length(clipIndex);
2218         service.unlock();
2219     } else if (speed == 1.0 && strobe < 2) {
2220         service.lock();
2221
2222         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2223         trackPlaylist.consolidate_blanks(0);
2224
2225         // Check that the blank space is long enough for our new duration
2226         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2227         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2228
2229         Mlt::Producer *cut;
2230         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2231         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2232             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2233             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2234         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2235
2236         // move all effects to the correct producer
2237         mltPasteEffects(clip, cut);
2238
2239         trackPlaylist.insert_at(startPos, cut, 1);
2240         delete cut;
2241         delete clip;
2242         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2243         newLength = trackPlaylist.clip_length(clipIndex);
2244         service.unlock();
2245
2246     } else if (serv == "framebuffer") {
2247         service.lock();
2248         QString url = QString::fromUtf8(clipparent.get("resource"));
2249         url = url.section('?', 0, 0);
2250         url.append('?' + m_locale.toString(speed));
2251         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2252         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2253         if (!slowprod || slowprod->get_producer() == NULL) {
2254             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2255             slowprod->set("strobe", strobe);
2256             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2257             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2258             slowprod->set("id", producerid.toUtf8().constData());
2259             // copy producer props
2260             double ar = original->parent().get_double("force_aspect_ratio");
2261             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2262             double fps = original->parent().get_double("force_fps");
2263             if (fps != 0.0) slowprod->set("force_fps", fps);
2264             if (original->parent().get("force_progressive"))
2265                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2266             if (original->parent().get("force_tff"))
2267                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2268             int threads = original->parent().get_int("threads");
2269             if (threads != 0) slowprod->set("threads", threads);
2270             int ix = original->parent().get_int("video_index");
2271             if (ix != 0) slowprod->set("video_index", ix);
2272             int colorspace = original->parent().get_int("force_colorspace");
2273             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2274             int full_luma = original->parent().get_int("set.force_full_luma");
2275             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2276             m_slowmotionProducers.insert(url, slowprod);
2277         }
2278         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2279         trackPlaylist.consolidate_blanks(0);
2280
2281         GenTime duration = speedIndependantInfo.cropDuration / speed;
2282         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2283
2284         // Check that the blank space is long enough for our new duration
2285         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2286         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2287
2288         Mlt::Producer *cut;
2289         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2290             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2291             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2292         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2293
2294         // move all effects to the correct producer
2295         mltPasteEffects(clip, cut);
2296
2297         trackPlaylist.insert_at(startPos, cut, 1);
2298         delete cut;
2299         delete clip;
2300         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2301         newLength = trackPlaylist.clip_length(clipIndex);
2302
2303         service.unlock();
2304     }
2305     delete original;
2306     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2307     return newLength;
2308 }
2309
2310 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2311 {
2312     Mlt::Service service(m_mltProducer->parent().get_service());
2313     bool success = false;
2314     Mlt::Tractor tractor(service);
2315     Mlt::Producer trackProducer(tractor.track(track));
2316     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2317     Mlt::Service clipService(trackPlaylist.get_service());
2318
2319     service.lock();
2320     int ct = 0;
2321     Mlt::Filter *filter = clipService.filter(ct);
2322     while (filter) {
2323         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2324             if (clipService.detach(*filter) == 0) success = true;
2325         } else if (updateIndex) {
2326             // Adjust the other effects index
2327             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2328             ct++;
2329         } else ct++;
2330         filter = clipService.filter(ct);
2331     }
2332     service.unlock();
2333     refresh();
2334     return success;
2335 }
2336
2337 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2338 {
2339     if (position < GenTime()) {
2340         // Remove track effect
2341         return mltRemoveTrackEffect(track, index, updateIndex);
2342     }
2343     Mlt::Service service(m_mltProducer->parent().get_service());
2344     bool success = false;
2345     Mlt::Tractor tractor(service);
2346     Mlt::Producer trackProducer(tractor.track(track));
2347     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2348
2349     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2350     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2351     if (!clip) {
2352         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2353         return false;
2354     }
2355
2356     Mlt::Service clipService(clip->get_service());
2357     int duration = clip->get_playtime();
2358     if (doRefresh) {
2359         // Check if clip is visible in monitor
2360         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2361         if (diff < 0 || diff > duration) doRefresh = false;
2362     }
2363     delete clip;
2364
2365     service.lock();
2366     int ct = 0;
2367     Mlt::Filter *filter = clipService.filter(ct);
2368     while (filter) {
2369         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2370             if (clipService.detach(*filter) == 0) success = true;
2371             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2372         } else if (updateIndex) {
2373             // Adjust the other effects index
2374             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2375             ct++;
2376         } else ct++;
2377         filter = clipService.filter(ct);
2378     }
2379     service.unlock();
2380     if (doRefresh) refresh();
2381     return success;
2382 }
2383
2384 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2385 {
2386     Mlt::Service service(m_mltProducer->parent().get_service());
2387     Mlt::Tractor tractor(service);
2388     Mlt::Producer trackProducer(tractor.track(track));
2389     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2390     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2391     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2392 }
2393
2394
2395 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2396 {
2397
2398     Mlt::Service service(m_mltProducer->parent().get_service());
2399
2400     Mlt::Tractor tractor(service);
2401     Mlt::Producer trackProducer(tractor.track(track));
2402     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2403
2404     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2405     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2406     if (!clip) {
2407         return false;
2408     }
2409
2410     Mlt::Service clipService(clip->get_service());
2411     int duration = clip->get_playtime();
2412     if (doRefresh) {
2413         // Check if clip is visible in monitor
2414         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2415         if (diff < 0 || diff > duration) doRefresh = false;
2416     }
2417     delete clip;
2418     return mltAddEffect(clipService, params, duration, doRefresh);
2419 }
2420
2421 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2422 {
2423     bool updateIndex = false;
2424     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2425     const QString region =  params.paramValue("region");
2426     int ct = 0;
2427     service.lock();
2428
2429     Mlt::Filter *filter = service.filter(ct);
2430     while (filter) {
2431         if (filter->get_int("kdenlive_ix") == filter_ix) {
2432             // A filter at that position already existed, so we will increase all indexes later
2433             updateIndex = true;
2434             break;
2435         }
2436         ct++;
2437         filter = service.filter(ct);
2438     }
2439
2440     if (params.paramValue("id") == "speed") {
2441         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2442         ct = 0;
2443         filter = service.filter(ct);
2444         while (filter) {
2445             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2446                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2447             }
2448             ct++;
2449             filter = service.filter(ct);
2450         }
2451         service.unlock();
2452         if (doRefresh) refresh();
2453         return true;
2454     }
2455
2456
2457     // temporarily remove all effects after insert point
2458     QList <Mlt::Filter *> filtersList;
2459     ct = 0;
2460     filter = service.filter(ct);
2461     while (filter) {
2462         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2463             filtersList.append(filter);
2464             service.detach(*filter);
2465         } else ct++;
2466         filter = service.filter(ct);
2467     }
2468
2469     // create filter
2470     QString tag =  params.paramValue("tag");
2471     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2472     char *filterTag = qstrdup(tag.toUtf8().constData());
2473     char *filterId = qstrdup(params.paramValue("id").toUtf8().constData());
2474     QHash<QString, QString>::Iterator it;
2475     QString kfr = params.paramValue("keyframes");
2476
2477     if (!kfr.isEmpty()) {
2478         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2479         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2480         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2481         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2482         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2483         //double max = params.paramValue("max").toDouble();
2484         double min = params.paramValue("min").toDouble();
2485         double factor = params.paramValue("factor", "1").toDouble();
2486         double paramOffset = params.paramValue("offset", "0").toDouble();
2487         params.removeParam("starttag");
2488         params.removeParam("endtag");
2489         params.removeParam("keyframes");
2490         params.removeParam("min");
2491         params.removeParam("max");
2492         params.removeParam("factor");
2493         params.removeParam("offset");
2494         int offset = 0;
2495         // Special case, only one keyframe, means we want a constant value
2496         if (keyFrames.count() == 1) {
2497             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2498             if (filter && filter->is_valid()) {
2499                 filter->set("kdenlive_id", filterId);
2500                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2501                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2502                 for (int j = 0; j < params.count(); j++) {
2503                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2504                 }
2505                 filter->set("in", x1);
2506                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2507                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2508                 service.attach(*filter);
2509             }
2510         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2511                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2512                 if (filter && filter->is_valid()) {
2513                     filter->set("kdenlive_id", filterId);
2514                     int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2515                     double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2516                     int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2517                     double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2518                     if (x2 == -1) x2 = duration;
2519
2520                     for (int j = 0; j < params.count(); j++) {
2521                         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2522                     }
2523
2524                     filter->set("in", x1);
2525                     filter->set("out", x2);
2526                     //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2527                     filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2528                     filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2529                     service.attach(*filter);
2530                     offset = 1;
2531                 }
2532             }
2533         delete[] starttag;
2534         delete[] endtag;
2535     } else {
2536         Mlt::Filter *filter;
2537         QString prefix;
2538         if (!region.isEmpty()) {
2539             filter = new Mlt::Filter(*m_mltProfile, "region");
2540         } else filter = new Mlt::Filter(*m_mltProfile, filterTag);
2541         if (filter && filter->is_valid()) {
2542             filter->set("kdenlive_id", filterId);
2543             if (!region.isEmpty()) {
2544                 filter->set("resource", region.toUtf8().constData());
2545                 filter->set("kdenlive_ix", params.paramValue("kdenlive_ix").toUtf8().constData());
2546                 filter->set("filter0", filterTag);
2547                 prefix = "filter0.";
2548                 params.removeParam("id");
2549                 params.removeParam("region");
2550                 params.removeParam("kdenlive_ix");
2551             }
2552         } else {
2553             kDebug() << "filter is NULL";
2554             service.unlock();
2555             return false;
2556         }
2557         params.removeParam("kdenlive_id");
2558         if (params.hasParam("_sync_in_out")) {
2559             // This effect must sync in / out with parent clip
2560             params.removeParam("_sync_in_out");
2561             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2562         }
2563
2564         for (int j = 0; j < params.count(); j++) {
2565             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2566         }
2567
2568         if (tag == "sox") {
2569             QString effectArgs = params.paramValue("id").section('_', 1);
2570
2571             params.removeParam("id");
2572             params.removeParam("kdenlive_ix");
2573             params.removeParam("tag");
2574             params.removeParam("disable");
2575             params.removeParam("region");
2576
2577             for (int j = 0; j < params.count(); j++) {
2578                 effectArgs.append(' ' + params.at(j).value());
2579             }
2580             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2581             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2582         }
2583
2584         // attach filter to the clip
2585         service.attach(*filter);
2586     }
2587     delete[] filterId;
2588     delete[] filterTag;
2589
2590     // re-add following filters
2591     for (int i = 0; i < filtersList.count(); i++) {
2592         Mlt::Filter *filter = filtersList.at(i);
2593         if (updateIndex)
2594             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2595         service.attach(*filter);
2596     }
2597     service.unlock();
2598     if (doRefresh) refresh();
2599     return true;
2600 }
2601
2602 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
2603 {
2604     Mlt::Service service(m_mltProducer->parent().get_service());
2605     Mlt::Tractor tractor(service);
2606     Mlt::Producer trackProducer(tractor.track(track));
2607     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2608     Mlt::Service clipService(trackPlaylist.get_service());
2609     int ct = 0;
2610     QString index = params.paramValue("kdenlive_ix");
2611     QString tag =  params.paramValue("tag");
2612
2613     Mlt::Filter *filter = clipService.filter(ct);
2614     while (filter) {
2615         if (filter->get_int("kdenlive_ix") == index.toInt()) {
2616             break;
2617         }
2618         ct++;
2619         filter = clipService.filter(ct);
2620     }
2621
2622     if (!filter) {
2623         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2624         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2625
2626         bool success = false;//mltAddTrackEffect(track, params);
2627         return success;
2628     }
2629     QString prefix;
2630     QString ser = filter->get("mlt_service");
2631     if (ser == "region") prefix = "filter0.";
2632     service.lock();
2633     for (int j = 0; j < params.count(); j++) {
2634         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2635     }
2636     service.unlock();
2637
2638     refresh();
2639     return true;
2640
2641 }
2642
2643 bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList params)
2644 {
2645     int index = params.paramValue("kdenlive_ix").toInt();
2646     QString tag =  params.paramValue("tag");
2647
2648     if (!params.paramValue("keyframes").isEmpty() || /*it.key().startsWith("#") || */tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle" || params.hasParam("region")) {
2649         // This is a keyframe effect, to edit it, we remove it and re-add it.
2650         bool success = mltRemoveEffect(track, position, index, false);
2651 //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
2652         if (position < GenTime())
2653             success = mltAddTrackEffect(track, params);
2654         else
2655             success = mltAddEffect(track, position, params);
2656 //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
2657         return success;
2658     }
2659     if (position < GenTime()) {
2660         return mltEditTrackEffect(track, params);
2661     }
2662     // find filter
2663     Mlt::Service service(m_mltProducer->parent().get_service());
2664     Mlt::Tractor tractor(service);
2665     Mlt::Producer trackProducer(tractor.track(track));
2666     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2667
2668     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2669     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2670     if (!clip) {
2671         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2672         return false;
2673     }
2674
2675     int duration = clip->get_playtime();
2676     bool doRefresh = true;
2677     // Check if clip is visible in monitor
2678     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2679     if (diff < 0 || diff > duration)
2680         doRefresh = false;
2681     int ct = 0;
2682
2683     Mlt::Filter *filter = clip->filter(ct);
2684     while (filter) {
2685         if (filter->get_int("kdenlive_ix") == index) {
2686             break;
2687         }
2688         ct++;
2689         filter = clip->filter(ct);
2690     }
2691
2692     if (!filter) {
2693         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2694         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2695
2696         bool success = mltAddEffect(track, position, params);
2697         return success;
2698     }
2699     QString prefix;
2700     QString ser = filter->get("mlt_service");
2701     if (ser == "region") prefix = "filter0.";
2702     if (params.hasParam("_sync_in_out")) {
2703         // This effect must sync in / out with parent clip
2704         params.removeParam("_sync_in_out");
2705         filter->set_in_and_out(clip->get_in(), clip->get_out());
2706     }
2707     service.lock();
2708     for (int j = 0; j < params.count(); j++) {
2709         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2710     }   
2711
2712     delete clip;
2713     service.unlock();
2714
2715     if (doRefresh) refresh();
2716     return true;
2717 }
2718
2719 void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
2720 {
2721     Mlt::Service service(m_mltProducer->parent().get_service());
2722     Mlt::Tractor tractor(service);
2723     Mlt::Producer trackProducer(tractor.track(track));
2724     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2725
2726     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2727     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2728     if (!clip) {
2729         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2730         return;
2731     }
2732
2733     Mlt::Service clipService(clip->get_service());
2734     int duration = clip->get_playtime();
2735     bool doRefresh = true;
2736     // Check if clip is visible in monitor
2737     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2738     if (diff < 0 || diff > duration) doRefresh = false;
2739     delete clip;
2740
2741     int ct = 0;
2742     Mlt::Filter *filter = clipService.filter(ct);
2743     while (filter) {
2744         int pos = filter->get_int("kdenlive_ix");
2745         if (pos == oldPos) {
2746             filter->set("kdenlive_ix", newPos);
2747         } else ct++;
2748         filter = clipService.filter(ct);
2749     }
2750     if (doRefresh) refresh();
2751 }
2752
2753 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
2754 {
2755     if (position < GenTime()) {
2756         mltMoveTrackEffect(track, oldPos, newPos);
2757         return;
2758     }
2759     Mlt::Service service(m_mltProducer->parent().get_service());
2760     Mlt::Tractor tractor(service);
2761     Mlt::Producer trackProducer(tractor.track(track));
2762     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2763
2764     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2765     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2766     if (!clip) {
2767         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2768         return;
2769     }
2770
2771     Mlt::Service clipService(clip->get_service());
2772     int duration = clip->get_playtime();
2773     bool doRefresh = true;
2774     // Check if clip is visible in monitor
2775     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2776     if (diff < 0 || diff > duration) doRefresh = false;
2777     delete clip;
2778
2779     int ct = 0;
2780     QList <Mlt::Filter *> filtersList;
2781     Mlt::Filter *filter = clipService.filter(ct);
2782     bool found = false;
2783     if (newPos > oldPos) {
2784         while (filter) {
2785             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
2786                 filter->set("kdenlive_ix", newPos);
2787                 filtersList.append(filter);
2788                 clipService.detach(*filter);
2789                 filter = clipService.filter(ct);
2790                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
2791                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2792                     ct++;
2793                     filter = clipService.filter(ct);
2794                 }
2795                 found = true;
2796             }
2797             if (filter && filter->get_int("kdenlive_ix") > newPos) {
2798                 filtersList.append(filter);
2799                 clipService.detach(*filter);
2800             } else ct++;
2801             filter = clipService.filter(ct);
2802         }
2803     } else {
2804         while (filter) {
2805             if (filter->get_int("kdenlive_ix") == oldPos) {
2806                 filter->set("kdenlive_ix", newPos);
2807                 filtersList.append(filter);
2808                 clipService.detach(*filter);
2809             } else ct++;
2810             filter = clipService.filter(ct);
2811         }
2812
2813         ct = 0;
2814         filter = clipService.filter(ct);
2815         while (filter) {
2816             int pos = filter->get_int("kdenlive_ix");
2817             if (pos >= newPos) {
2818                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
2819                 filtersList.append(filter);
2820                 clipService.detach(*filter);
2821             } else ct++;
2822             filter = clipService.filter(ct);
2823         }
2824     }
2825
2826     for (int i = 0; i < filtersList.count(); i++) {
2827         clipService.attach(*(filtersList.at(i)));
2828     }
2829
2830     if (doRefresh) refresh();
2831 }
2832
2833 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
2834 {
2835     Mlt::Service service(m_mltProducer->parent().get_service());
2836     Mlt::Tractor tractor(service);
2837     Mlt::Producer trackProducer(tractor.track(track));
2838     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2839     Mlt::Service clipService(trackPlaylist.get_service());
2840     int ct = 0;
2841     QList <Mlt::Filter *> filtersList;
2842     Mlt::Filter *filter = clipService.filter(ct);
2843     bool found = false;
2844     if (newPos > oldPos) {
2845         while (filter) {
2846             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
2847                 filter->set("kdenlive_ix", newPos);
2848                 filtersList.append(filter);
2849                 clipService.detach(*filter);
2850                 filter = clipService.filter(ct);
2851                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
2852                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2853                     ct++;
2854                     filter = clipService.filter(ct);
2855                 }
2856                 found = true;
2857             }
2858             if (filter && filter->get_int("kdenlive_ix") > newPos) {
2859                 filtersList.append(filter);
2860                 clipService.detach(*filter);
2861             } else ct++;
2862             filter = clipService.filter(ct);
2863         }
2864     } else {
2865         while (filter) {
2866             if (filter->get_int("kdenlive_ix") == oldPos) {
2867                 filter->set("kdenlive_ix", newPos);
2868                 filtersList.append(filter);
2869                 clipService.detach(*filter);
2870             } else ct++;
2871             filter = clipService.filter(ct);
2872         }
2873
2874         ct = 0;
2875         filter = clipService.filter(ct);
2876         while (filter) {
2877             int pos = filter->get_int("kdenlive_ix");
2878             if (pos >= newPos) {
2879                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
2880                 filtersList.append(filter);
2881                 clipService.detach(*filter);
2882             } else ct++;
2883             filter = clipService.filter(ct);
2884         }
2885     }
2886
2887     for (int i = 0; i < filtersList.count(); i++) {
2888         clipService.attach(*(filtersList.at(i)));
2889     }
2890     refresh();
2891 }
2892
2893 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
2894 {
2895     Mlt::Service service(m_mltProducer->parent().get_service());
2896     Mlt::Tractor tractor(service);
2897     Mlt::Producer trackProducer(tractor.track(info.track));
2898     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2899
2900     /* // Display playlist info
2901     kDebug()<<"////////////  BEFORE RESIZE";
2902     for (int i = 0; i < trackPlaylist.count(); i++) {
2903     int blankStart = trackPlaylist.clip_start(i);
2904     int blankDuration = trackPlaylist.clip_length(i) - 1;
2905     QString blk;
2906     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2907     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2908     }*/
2909
2910     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
2911         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
2912         return false;
2913     }
2914     service.lock();
2915     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
2916     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
2917     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2918
2919     int previousStart = clip->get_in();
2920     int newDuration = (int) clipDuration.frames(m_fps) - 1;
2921     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
2922
2923     int currentOut = newDuration + previousStart;
2924     if (currentOut > clip->get_length()) {
2925         clip->parent().set("length", currentOut + 1);
2926         clip->parent().set("out", currentOut);
2927         clip->set("length", currentOut + 1);
2928     }
2929
2930     /*if (newDuration > clip->get_out()) {
2931         clip->parent().set_in_and_out(0, newDuration + 1);
2932         clip->set_in_and_out(0, newDuration + 1);
2933     }*/
2934     delete clip;
2935     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
2936     trackPlaylist.consolidate_blanks(0);
2937     // skip to next clip
2938     clipIndex++;
2939     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
2940     if (diff > 0) {
2941         // clip was made longer, trim next blank if there is one.
2942         if (clipIndex < trackPlaylist.count()) {
2943             // If this is not the last clip in playlist
2944             if (trackPlaylist.is_blank(clipIndex)) {
2945                 int blankStart = trackPlaylist.clip_start(clipIndex);
2946                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2947                 if (diff > blankDuration) {
2948                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
2949                 }
2950                 if (diff - blankDuration == 0) {
2951                     trackPlaylist.remove(clipIndex);
2952                 } else trackPlaylist.remove_region(blankStart, diff);
2953             } else {
2954                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
2955             }
2956         }
2957     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
2958     trackPlaylist.consolidate_blanks(0);
2959     service.unlock();
2960
2961     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
2962     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
2963         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
2964         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
2965         ItemInfo transpinfo;
2966         transpinfo.startPos = info.startPos;
2967         transpinfo.endPos = info.startPos + clipDuration;
2968         transpinfo.track = info.track;
2969         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
2970     }*/
2971     m_mltConsumer->set("refresh", 1);
2972     return true;
2973 }
2974
2975 void Render::mltChangeTrackState(int track, bool mute, bool blind)
2976 {
2977     Mlt::Service service(m_mltProducer->parent().get_service());
2978     Mlt::Tractor tractor(service);
2979     Mlt::Producer trackProducer(tractor.track(track));
2980
2981     // Make sure muting will not produce problems with our audio mixing transition,
2982     // because audio mixing is done between each track and the lowest one
2983     bool audioMixingBroken = false;
2984     if (mute && trackProducer.get_int("hide") < 2 ) {
2985             // We mute a track with sound
2986             if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
2987             kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
2988     }
2989     else if (!mute && trackProducer.get_int("hide") > 1 ) {
2990             // We un-mute a previously muted track
2991             if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
2992     }
2993
2994     if (mute) {
2995         if (blind) trackProducer.set("hide", 3);
2996         else trackProducer.set("hide", 2);
2997     } else if (blind) {
2998         trackProducer.set("hide", 1);
2999     } else {
3000         trackProducer.set("hide", 0);
3001     }
3002     if (audioMixingBroken) fixAudioMixing(tractor);
3003     
3004     tractor.multitrack()->refresh();
3005     tractor.refresh();
3006     refresh();
3007 }
3008
3009 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3010 {
3011     for (int i = 1; i < tractor.count(); i++) {
3012         Mlt::Producer trackProducer(tractor.track(i));
3013         if (trackProducer.get_int("hide") < 2) return i;
3014     }
3015     return tractor.count() - 1;
3016 }
3017
3018 void Render::fixAudioMixing(Mlt::Tractor tractor)
3019 {
3020     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3021     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3022
3023     mlt_service serv = m_mltProducer->parent().get_service();
3024     Mlt::Field *field = tractor.field();
3025     mlt_service_lock(serv);
3026
3027     mlt_service nextservice = mlt_service_get_producer(serv);
3028     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3029     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3030     QString resource = mlt_properties_get(properties, "mlt_service");
3031
3032     mlt_service nextservicetodisconnect;
3033      // Delete all audio mixing transitions
3034     while (mlt_type == "transition") {
3035         if (resource == "mix") {
3036             nextservicetodisconnect = nextservice;
3037             nextservice = mlt_service_producer(nextservice);
3038             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3039         }
3040         else nextservice = mlt_service_producer(nextservice);
3041         if (nextservice == NULL) break;
3042         properties = MLT_SERVICE_PROPERTIES(nextservice);
3043         mlt_type = mlt_properties_get(properties, "mlt_type");
3044         resource = mlt_properties_get(properties, "mlt_service");
3045     }
3046
3047     // Re-add correct audio transitions
3048     for (int i = lowestTrack + 1; i < tractor.count(); i++) {
3049         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3050         transition->set("always_active", 1);
3051         transition->set("combine", 1);
3052         transition->set("internal_added", 237);
3053         field->plant_transition(*transition, lowestTrack, i);
3054     }
3055     mlt_service_unlock(serv);
3056 }
3057
3058 bool Render::mltResizeClipCrop(ItemInfo info, GenTime diff)
3059 {
3060     Mlt::Service service(m_mltProducer->parent().get_service());
3061     int frameOffset = (int) diff.frames(m_fps);
3062     Mlt::Tractor tractor(service);
3063     Mlt::Producer trackProducer(tractor.track(info.track));
3064     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3065     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3066         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3067         return false;
3068     }
3069     service.lock();
3070     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3071     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3072     if (clip == NULL) {
3073         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3074         service.unlock();
3075         return false;
3076     }
3077     int previousStart = clip->get_in();
3078     int previousOut = clip->get_out();
3079     delete clip;
3080     trackPlaylist.resize_clip(clipIndex, previousStart + frameOffset, previousOut + frameOffset);
3081     service.unlock();
3082     m_mltConsumer->set("refresh", 1);
3083     return true;
3084 }
3085
3086 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3087 {
3088     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3089     Mlt::Service service(m_mltProducer->parent().get_service());
3090     int moveFrame = (int) diff.frames(m_fps);
3091     Mlt::Tractor tractor(service);
3092     Mlt::Producer trackProducer(tractor.track(info.track));
3093     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3094     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3095         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3096         return false;
3097     }
3098     service.lock();
3099     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3100     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3101     if (clip == NULL || clip->is_blank()) {
3102         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3103         service.unlock();
3104         return false;
3105     }
3106     int previousStart = clip->get_in();
3107     int previousOut = clip->get_out();
3108
3109     previousStart += moveFrame;
3110
3111     if (previousStart < 0) {
3112         // this is possible for images and color clips
3113         previousOut -= previousStart;
3114         previousStart = 0;
3115     }
3116
3117     int length = previousOut + 1;
3118     if (length > clip->get_length()) {
3119         clip->parent().set("length", length + 1);
3120         clip->parent().set("out", length);
3121         clip->set("length", length + 1);
3122     }
3123     delete clip;
3124
3125     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3126     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3127     if (moveFrame > 0) {
3128         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3129     } else {
3130         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3131         int blankIndex = clipIndex - 1;
3132         int blankLength = trackPlaylist.clip_length(blankIndex);
3133         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3134         if (! trackPlaylist.is_blank(blankIndex)) {
3135             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3136         }
3137         if (blankLength + moveFrame == 0)
3138             trackPlaylist.remove(blankIndex);
3139         else
3140             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3141     }
3142     trackPlaylist.consolidate_blanks(0);
3143     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3144         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3145         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3146         ItemInfo transpinfo;
3147         transpinfo.startPos = info.startPos + diff;
3148         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3149         transpinfo.track = info.track;
3150         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3151     }*/
3152     //m_mltConsumer->set("refresh", 1);
3153     service.unlock();
3154     m_mltConsumer->set("refresh", 1);
3155     return true;
3156 }
3157
3158 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3159 {
3160     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3161 }
3162
3163
3164 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3165 {
3166     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3167         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3168         return false;
3169     }
3170
3171     Mlt::Producer trackProducer(tractor->track(track));
3172     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3173     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3174     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3175     if (clipProducer == NULL || clipProducer->is_blank()) {
3176         kDebug() << "// ERROR UPDATING CLIP PROD";
3177         delete clipProducer;
3178         return false;
3179     }
3180     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3181     if (!clip || !clip->is_valid()) {
3182         if (clip) delete clip;
3183         delete clipProducer;
3184         return false;
3185     }
3186     // move all effects to the correct producer
3187     mltPasteEffects(clipProducer, clip);
3188     trackPlaylist.insert_at(pos, clip, 1);
3189     delete clip;
3190     delete clipProducer;
3191     return true;
3192 }
3193
3194 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3195 {
3196     Mlt::Service service(m_mltProducer->parent().get_service());
3197     if (service.type() != tractor_type) {
3198         kWarning() << "// TRACTOR PROBLEM";
3199         return false;
3200     }
3201
3202     Mlt::Tractor tractor(service);
3203     service.lock();
3204     Mlt::Producer trackProducer(tractor.track(startTrack));
3205     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3206     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3207     //kDebug() << "//////  LOOKING FOR CLIP TO MOVE, INDEX: " << clipIndex;
3208     bool checkLength = false;
3209     if (endTrack == startTrack) {
3210         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3211         if ((!overwrite && !trackPlaylist.is_blank_at(moveEnd)) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
3212             // error, destination is not empty
3213             if (clipProducer) {
3214                 if (!trackPlaylist.is_blank_at(moveEnd) && clipProducer->is_valid()) trackPlaylist.insert_at(moveStart, clipProducer, 1);
3215                 delete clipProducer;
3216             }
3217             //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3218             kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3219             service.unlock();
3220             return false;
3221         } else {
3222             trackPlaylist.consolidate_blanks(0);
3223             if (overwrite) {
3224                 trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3225                 int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
3226                 trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
3227             }
3228             int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3229             trackPlaylist.consolidate_blanks(1);
3230             delete clipProducer;
3231             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3232             mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3233             }*/
3234             if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
3235         }
3236         //service.unlock();
3237     } else {
3238         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3239         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3240         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3241             // error, destination is not empty
3242             service.unlock();
3243             return false;
3244         } else {
3245             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3246             if (!clipProducer || clipProducer->is_blank()) {
3247                 // error, destination is not empty
3248                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3249                 if (clipProducer) delete clipProducer;
3250                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3251                 service.unlock();
3252                 return false;
3253             }
3254             trackPlaylist.consolidate_blanks(0);
3255             destTrackPlaylist.consolidate_blanks(1);
3256             Mlt::Producer *clip;
3257             // check if we are moving a slowmotion producer
3258             QString serv = clipProducer->parent().get("mlt_service");
3259             QString currentid = clipProducer->parent().get("id");
3260             if (serv == "framebuffer" || currentid.endsWith("_video")) {
3261                 clip = clipProducer;
3262             } else {
3263                 if (prod == NULL) {
3264                     // Special case: prod is null when using placeholder clips.
3265                     // in that case, use the producer existing in playlist. Note that
3266                     // it will bypass the one producer per track logic and might cause
3267                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3268                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3269                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3270             }
3271
3272             // move all effects to the correct producer
3273             mltPasteEffects(clipProducer, clip);
3274
3275             if (overwrite) {
3276                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3277                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3278                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3279             }
3280
3281             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3282
3283             if (clip == clipProducer) {
3284                 delete clip;
3285                 clip = NULL;
3286             } else {
3287                 delete clip;
3288                 delete clipProducer;
3289             }
3290             destTrackPlaylist.consolidate_blanks(0);
3291             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3292                 kDebug() << "//////// moving clip transparency";
3293                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3294             }*/
3295             if (clipIndex > trackPlaylist.count()) checkLength = true;
3296             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3297         }
3298     }
3299     service.unlock();
3300     if (checkLength) mltCheckLength(&tractor);
3301     //askForRefresh();
3302     //m_mltConsumer->set("refresh", 1);
3303     return true;
3304 }
3305
3306
3307 QList <int> Render::checkTrackSequence(int track)
3308 {
3309     QList <int> list;
3310     Mlt::Service service(m_mltProducer->parent().get_service());
3311     if (service.type() != tractor_type) {
3312         kWarning() << "// TRACTOR PROBLEM";
3313         return list;
3314     }
3315     Mlt::Tractor tractor(service);
3316     service.lock();
3317     Mlt::Producer trackProducer(tractor.track(track));
3318     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3319     int clipNb = trackPlaylist.count();
3320     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3321     for (int i = 0; i < clipNb; i++) {
3322         Mlt::Producer *c = trackPlaylist.get_clip(i);
3323         int pos = trackPlaylist.clip_start(i);
3324         if (!list.contains(pos)) list.append(pos);
3325         pos += c->get_playtime();
3326         if (!list.contains(pos)) list.append(pos);
3327         delete c;
3328     }
3329     return list;
3330 }
3331
3332 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3333 {
3334     int new_in = (int)newIn.frames(m_fps);
3335     int new_out = (int)newOut.frames(m_fps) - 1;
3336     if (new_in >= new_out) return false;
3337     int old_in = (int)oldIn.frames(m_fps);
3338     int old_out = (int)oldOut.frames(m_fps) - 1;
3339
3340     Mlt::Service service(m_mltProducer->parent().get_service());
3341     Mlt::Tractor tractor(service);
3342     Mlt::Field *field = tractor.field();
3343
3344     bool doRefresh = true;
3345     // Check if clip is visible in monitor
3346     int diff = old_out - m_mltProducer->position();
3347     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3348     if (doRefresh) {
3349         diff = new_out - m_mltProducer->position();
3350         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3351     }
3352     service.lock();
3353
3354     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3355     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3356     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3357     QString resource = mlt_properties_get(properties, "mlt_service");
3358     int old_pos = (int)(old_in + old_out) / 2;
3359     bool found = false;
3360
3361     while (mlt_type == "transition") {
3362         Mlt::Transition transition((mlt_transition) nextservice);
3363         int currentTrack = transition.get_b_track();
3364         int currentIn = (int) transition.get_in();
3365         int currentOut = (int) transition.get_out();
3366
3367         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3368             found = true;
3369             if (newTrack - startTrack != 0) {
3370                 Mlt::Properties trans_props(transition.get_properties());
3371                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3372                 Mlt::Properties new_trans_props(new_transition.get_properties());
3373                 new_trans_props.inherit(trans_props);
3374                 new_transition.set_in_and_out(new_in, new_out);
3375                 field->disconnect_service(transition);
3376                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3377                 //field->plant_transition(new_transition, newTransitionTrack, newTrack);
3378             } else transition.set_in_and_out(new_in, new_out);
3379             break;
3380         }
3381         nextservice = mlt_service_producer(nextservice);
3382         if (nextservice == NULL) break;
3383         properties = MLT_SERVICE_PROPERTIES(nextservice);
3384         mlt_type = mlt_properties_get(properties, "mlt_type");
3385         resource = mlt_properties_get(properties, "mlt_service");
3386     }
3387     service.unlock();
3388     if (doRefresh) refresh();
3389     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3390     return found;
3391 }
3392
3393
3394 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3395 {
3396     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3397     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3398     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3399     QString resource = mlt_properties_get(properties, "mlt_service");
3400     QList <Mlt::Transition *> trList;
3401
3402     while (mlt_type == "transition") {
3403         Mlt::Transition transition((mlt_transition) nextservice);
3404         int aTrack = transition.get_a_track();
3405         int bTrack = transition.get_b_track();
3406         if (resource != "mix" && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3407             Mlt::Properties trans_props(transition.get_properties());
3408             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3409             Mlt::Properties new_trans_props(cp->get_properties());
3410             new_trans_props.inherit(trans_props);
3411             trList.append(cp);
3412             field->disconnect_service(transition);
3413         }
3414         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3415
3416         nextservice = mlt_service_producer(nextservice);
3417         if (nextservice == NULL) break;
3418         properties = MLT_SERVICE_PROPERTIES(nextservice);
3419         mlt_type = mlt_properties_get(properties, "mlt_type");
3420         resource = mlt_properties_get(properties, "mlt_service");
3421     }
3422     field->plant_transition(tr, a_track, b_track);
3423
3424     // re-add upper transitions
3425     for (int i = trList.count() - 1; i >= 0; i--) {
3426         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3427         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3428     }
3429 }
3430
3431 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3432 {
3433     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3434     else {
3435         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3436         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3437         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3438     }
3439
3440     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3441 }
3442
3443 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3444 {
3445     mlt_service serv = m_mltProducer->parent().get_service();
3446     mlt_service_lock(serv);
3447
3448     mlt_service nextservice = mlt_service_get_producer(serv);
3449     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3450     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3451     QString resource = mlt_properties_get(properties, "mlt_service");
3452     int in_pos = (int) in.frames(m_fps);
3453     int out_pos = (int) out.frames(m_fps) - 1;
3454
3455     while (mlt_type == "transition") {
3456         mlt_transition tr = (mlt_transition) nextservice;
3457         int currentTrack = mlt_transition_get_b_track(tr);
3458         int currentBTrack = mlt_transition_get_a_track(tr);
3459         int currentIn = (int) mlt_transition_get_in(tr);
3460         int currentOut = (int) mlt_transition_get_out(tr);
3461
3462         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
3463         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
3464             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
3465             QMap<QString, QString>::Iterator it;
3466             QString key;
3467             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
3468
3469             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
3470             if (currentId != xml.attribute("id")) {
3471                 // The transition ID is not the same, so reset all properties
3472                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
3473                 // Cleanup previous properties
3474                 QStringList permanentProps;
3475                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
3476                 permanentProps << "out" << "a_track" << "b_track";
3477                 for (int i = 0; i < mlt_properties_count(transproperties); i++) {
3478                     QString propName = mlt_properties_get_name(transproperties, i);
3479                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
3480                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
3481                     }
3482                 }
3483             }
3484
3485             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
3486             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
3487
3488             if (currentBTrack != a_track) {
3489                 mlt_properties_set_int(transproperties, "a_track", a_track);
3490             }
3491             for (it = map.begin(); it != map.end(); ++it) {
3492                 key = it.key();
3493                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
3494                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
3495                 //filter->set("kdenlive_id", id);
3496             }
3497             break;
3498         }
3499         nextservice = mlt_service_producer(nextservice);
3500         if (nextservice == NULL) break;
3501         properties = MLT_SERVICE_PROPERTIES(nextservice);
3502         mlt_type = mlt_properties_get(properties, "mlt_type");
3503         resource = mlt_properties_get(properties, "mlt_service");
3504     }
3505     mlt_service_unlock(serv);
3506     //askForRefresh();
3507     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3508 }
3509
3510 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
3511 {
3512     mlt_service serv = m_mltProducer->parent().get_service();
3513     mlt_service_lock(serv);
3514
3515     Mlt::Service service(serv);
3516     Mlt::Tractor tractor(service);
3517     Mlt::Field *field = tractor.field();
3518
3519     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3520
3521     mlt_service nextservice = mlt_service_get_producer(serv);
3522     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3523     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3524     QString resource = mlt_properties_get(properties, "mlt_service");
3525
3526     const int old_pos = (int)((in + out).frames(m_fps) / 2);
3527     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
3528
3529     while (mlt_type == "transition") {
3530         mlt_transition tr = (mlt_transition) nextservice;
3531         int currentTrack = mlt_transition_get_b_track(tr);
3532         int currentIn = (int) mlt_transition_get_in(tr);
3533         int currentOut = (int) mlt_transition_get_out(tr);
3534         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3535
3536         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3537             mlt_field_disconnect_service(field->get_field(), nextservice);
3538             break;
3539         }
3540         nextservice = mlt_service_producer(nextservice);
3541         if (nextservice == NULL) break;
3542         properties = MLT_SERVICE_PROPERTIES(nextservice);
3543         mlt_type = mlt_properties_get(properties, "mlt_type");
3544         resource = mlt_properties_get(properties, "mlt_service");
3545     }
3546     mlt_service_unlock(serv);
3547     //askForRefresh();
3548     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3549 }
3550
3551 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
3552 {
3553     QDomNodeList attribs = xml.elementsByTagName("parameter");
3554     QMap<QString, QString> map;
3555     for (int i = 0; i < attribs.count(); i++) {
3556         QDomElement e = attribs.item(i).toElement();
3557         QString name = e.attribute("name");
3558         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
3559         map[name] = e.attribute("default");
3560         if (!e.attribute("value").isEmpty()) {
3561             map[name] = e.attribute("value");
3562         }
3563         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
3564             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
3565             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
3566         }
3567
3568         if (e.attribute("namedesc").contains(';')) {
3569             QString format = e.attribute("format");
3570             QStringList separators = format.split("%d", QString::SkipEmptyParts);
3571             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
3572             QString neu;
3573             QTextStream txtNeu(&neu);
3574             if (values.size() > 0)
3575                 txtNeu << (int)values[0].toDouble();
3576             int i = 0;
3577             for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
3578                 txtNeu << separators[i];
3579                 txtNeu << (int)(values[i+1].toDouble());
3580             }
3581             if (i < separators.size())
3582                 txtNeu << separators[i];
3583             map[e.attribute("name")] = neu;
3584         }
3585
3586     }
3587     return map;
3588 }
3589
3590 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
3591 {
3592     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
3593     Mlt::Service service(m_mltProducer->parent().get_service());
3594     Mlt::Tractor tractor(service);
3595     Mlt::Field *field = tractor.field();
3596
3597     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
3598     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
3599     transition->set("transparency", id);
3600     transition->set("fill", 1);
3601     transition->set("internal_added", 237);
3602     field->plant_transition(*transition, transitiontrack, info.track);
3603     refresh();
3604 }
3605
3606 void Render::mltDeleteTransparency(int pos, int track, int id)
3607 {
3608     Mlt::Service service(m_mltProducer->parent().get_service());
3609     Mlt::Tractor tractor(service);
3610     Mlt::Field *field = tractor.field();
3611
3612     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3613     mlt_service serv = m_mltProducer->parent().get_service();
3614
3615     mlt_service nextservice = mlt_service_get_producer(serv);
3616     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3617     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3618     QString resource = mlt_properties_get(properties, "mlt_service");
3619
3620     while (mlt_type == "transition") {
3621         mlt_transition tr = (mlt_transition) nextservice;
3622         int currentTrack = mlt_transition_get_b_track(tr);
3623         int currentIn = (int) mlt_transition_get_in(tr);
3624         int currentOut = (int) mlt_transition_get_out(tr);
3625         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3626         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3627
3628         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
3629             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
3630             mlt_field_disconnect_service(field->get_field(), nextservice);
3631             break;
3632         }
3633         nextservice = mlt_service_producer(nextservice);
3634         if (nextservice == NULL) break;
3635         properties = MLT_SERVICE_PROPERTIES(nextservice);
3636         mlt_type = mlt_properties_get(properties, "mlt_type");
3637         resource = mlt_properties_get(properties, "mlt_service");
3638     }
3639     //if (do_refresh) m_mltConsumer->set("refresh", 1);
3640 }
3641
3642 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
3643 {
3644     Mlt::Service service(m_mltProducer->parent().get_service());
3645     Mlt::Tractor tractor(service);
3646
3647     service.lock();
3648     m_mltConsumer->set("refresh", 0);
3649
3650     mlt_service serv = m_mltProducer->parent().get_service();
3651     mlt_service nextservice = mlt_service_get_producer(serv);
3652     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3653     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3654     QString resource = mlt_properties_get(properties, "mlt_service");
3655     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
3656     while (mlt_type == "transition") {
3657         mlt_transition tr = (mlt_transition) nextservice;
3658         int currentTrack = mlt_transition_get_b_track(tr);
3659         int currentIn = (int) mlt_transition_get_in(tr);
3660         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
3661         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3662         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
3663         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
3664             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
3665             mlt_transition_set_in_and_out(tr, newStart, newEnd);
3666             break;
3667         }
3668         nextservice = mlt_service_producer(nextservice);
3669         if (nextservice == NULL) break;
3670         properties = MLT_SERVICE_PROPERTIES(nextservice);
3671         mlt_type = mlt_properties_get(properties, "mlt_type");
3672         resource = mlt_properties_get(properties, "mlt_service");
3673     }
3674     service.unlock();
3675     m_mltConsumer->set("refresh", 1);
3676
3677 }
3678
3679 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
3680 {
3681     Mlt::Service service(m_mltProducer->parent().get_service());
3682     Mlt::Tractor tractor(service);
3683
3684     service.lock();
3685     m_mltConsumer->set("refresh", 0);
3686
3687     mlt_service serv = m_mltProducer->parent().get_service();
3688     mlt_service nextservice = mlt_service_get_producer(serv);
3689     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3690     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3691     QString resource = mlt_properties_get(properties, "mlt_service");
3692
3693     while (mlt_type == "transition") {
3694         mlt_transition tr = (mlt_transition) nextservice;
3695         int currentTrack = mlt_transition_get_b_track(tr);
3696         int currentaTrack = mlt_transition_get_a_track(tr);
3697         int currentIn = (int) mlt_transition_get_in(tr);
3698         int currentOut = (int) mlt_transition_get_out(tr);
3699         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
3700         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3701         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
3702         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
3703             kDebug() << "//////MOVING";
3704             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
3705             if (endTrack != startTrack) {
3706                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
3707                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
3708                 mlt_properties_set_int(properties, "b_track", endTrack);
3709             }
3710             break;
3711         }
3712         nextservice = mlt_service_producer(nextservice);
3713         if (nextservice == NULL) break;
3714         properties = MLT_SERVICE_PROPERTIES(nextservice);
3715         mlt_type = mlt_properties_get(properties, "mlt_type");
3716         resource = mlt_properties_get(properties, "mlt_service");
3717     }
3718     service.unlock();
3719     m_mltConsumer->set("refresh", 1);
3720 }
3721
3722
3723 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
3724 {
3725     if (in >= out) return false;
3726     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
3727     Mlt::Service service(m_mltProducer->parent().get_service());
3728
3729     Mlt::Tractor tractor(service);
3730     Mlt::Field *field = tractor.field();
3731
3732     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, tag.toUtf8().constData());
3733     if (out != GenTime())
3734         transition->set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
3735
3736     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
3737     QMap<QString, QString>::Iterator it;
3738     QString key;
3739     if (xml.attribute("automatic") == "1") transition->set("automatic", 1);
3740     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
3741     if (xml.hasAttribute("id"))
3742         transition->set("kdenlive_id", xml.attribute("id").toUtf8().constData());
3743     if (xml.hasAttribute("force_track"))
3744         transition->set("force_track", xml.attribute("force_track").toInt());
3745
3746     for (it = args.begin(); it != args.end(); ++it) {
3747         key = it.key();
3748         if (!it.value().isEmpty())
3749             transition->set(key.toUtf8().constData(), it.value().toUtf8().constData());
3750         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
3751     }
3752     // attach transition
3753     service.lock();
3754     mltPlantTransition(field, *transition, a_track, b_track);
3755     // field->plant_transition(*transition, a_track, b_track);
3756     service.unlock();
3757     if (do_refresh) refresh();
3758     return true;
3759 }
3760
3761 void Render::mltSavePlaylist()
3762 {
3763     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
3764     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
3765     fileConsumer.set("resource", "/tmp/playlist.mlt");
3766
3767     Mlt::Service service(m_mltProducer->get_service());
3768
3769     fileConsumer.connect(service);
3770     fileConsumer.start();
3771 }
3772
3773 const QList <Mlt::Producer *> Render::producersList()
3774 {
3775     QList <Mlt::Producer *> prods;
3776     if (m_mltProducer == NULL) return prods;
3777     Mlt::Service service(m_mltProducer->parent().get_service());
3778     if (service.type() != tractor_type) return prods;
3779     Mlt::Tractor tractor(service);
3780     QStringList ids;
3781
3782     int trackNb = tractor.count();
3783     for (int t = 1; t < trackNb; t++) {
3784         Mlt::Producer *tt = tractor.track(t);
3785         Mlt::Producer trackProducer(tt);
3786         delete tt;
3787         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3788         int clipNb = trackPlaylist.count();
3789         for (int i = 0; i < clipNb; i++) {
3790             Mlt::Producer *c = trackPlaylist.get_clip(i);
3791             if (c == NULL) continue;
3792             QString prodId = c->parent().get("id");
3793             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
3794                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
3795                 if (nprod) {
3796                     ids.append(prodId);
3797                     prods.append(nprod);
3798                 }
3799             }
3800             delete c;
3801         }
3802     }
3803     return prods;
3804 }
3805
3806 void Render::fillSlowMotionProducers()
3807 {
3808     if (m_mltProducer == NULL) return;
3809     Mlt::Service service(m_mltProducer->parent().get_service());
3810     if (service.type() != tractor_type) return;
3811
3812     Mlt::Tractor tractor(service);
3813
3814     int trackNb = tractor.count();
3815     for (int t = 1; t < trackNb; t++) {
3816         Mlt::Producer *tt = tractor.track(t);
3817         Mlt::Producer trackProducer(tt);
3818         delete tt;
3819         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3820         int clipNb = trackPlaylist.count();
3821         for (int i = 0; i < clipNb; i++) {
3822             Mlt::Producer *c = trackPlaylist.get_clip(i);
3823             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
3824             if (nprod) {
3825                 QString id = nprod->parent().get("id");
3826                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
3827                     // this is a slowmotion producer, add it to the list
3828                     QString url = QString::fromUtf8(nprod->get("resource"));
3829                     int strobe = nprod->get_int("strobe");
3830                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
3831                     if (!m_slowmotionProducers.contains(url)) {
3832                         m_slowmotionProducers.insert(url, nprod);
3833                     }
3834                 } else delete nprod;
3835             }
3836             delete c;
3837         }
3838     }
3839 }
3840
3841 void Render::mltInsertTrack(int ix, bool videoTrack)
3842 {
3843     blockSignals(true);
3844
3845     Mlt::Service service(m_mltProducer->parent().get_service());
3846     service.lock();
3847     if (service.type() != tractor_type) {
3848         kWarning() << "// TRACTOR PROBLEM";
3849         return;
3850     }
3851
3852     Mlt::Tractor tractor(service);
3853
3854     Mlt::Playlist playlist;
3855     int ct = tractor.count();
3856     if (ix > ct) {
3857         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
3858         ix = ct;
3859     }
3860
3861     int pos = ix;
3862     if (pos < ct) {
3863         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
3864         tractor.set_track(playlist, pos);
3865         Mlt::Producer newProd(tractor.track(pos));
3866         if (!videoTrack) newProd.set("hide", 1);
3867         pos++;
3868         for (; pos <= ct; pos++) {
3869             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
3870             tractor.set_track(*prodToMove, pos);
3871             prodToMove = prodToMove2;
3872         }
3873     } else {
3874         tractor.set_track(playlist, ix);
3875         Mlt::Producer newProd(tractor.track(ix));
3876         if (!videoTrack) newProd.set("hide", 1);
3877     }
3878     checkMaxThreads();
3879
3880     // Move transitions
3881     mlt_service serv = m_mltProducer->parent().get_service();
3882     mlt_service nextservice = mlt_service_get_producer(serv);
3883     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3884     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3885     QString resource = mlt_properties_get(properties, "mlt_service");
3886
3887     while (mlt_type == "transition") {
3888         if (resource != "mix") {
3889             mlt_transition tr = (mlt_transition) nextservice;
3890             int currentTrack = mlt_transition_get_b_track(tr);
3891             int currentaTrack = mlt_transition_get_a_track(tr);
3892             mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
3893
3894             if (currentTrack >= ix) {
3895                 mlt_properties_set_int(properties, "b_track", currentTrack + 1);
3896                 mlt_properties_set_int(properties, "a_track", currentaTrack + 1);
3897             }
3898         }
3899         nextservice = mlt_service_producer(nextservice);
3900         if (nextservice == NULL) break;
3901         properties = MLT_SERVICE_PROPERTIES(nextservice);
3902         mlt_type = mlt_properties_get(properties, "mlt_type");
3903         resource = mlt_properties_get(properties, "mlt_service");
3904     }
3905
3906     // Add audio mix transition to last track
3907     Mlt::Field *field = tractor.field();
3908     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3909     transition->set("a_track", 1);
3910     transition->set("b_track", ct);
3911     transition->set("always_active", 1);
3912     transition->set("internal_added", 237);
3913     transition->set("combine", 1);
3914     field->plant_transition(*transition, 1, ct);
3915     //mlt_service_unlock(m_mltConsumer->get_service());
3916     service.unlock();
3917     //tractor.multitrack()->refresh();
3918     //tractor.refresh();
3919     blockSignals(false);
3920 }
3921
3922
3923 void Render::mltDeleteTrack(int ix)
3924 {
3925     QDomDocument doc;
3926     doc.setContent(sceneList(), false);
3927     int tracksCount = doc.elementsByTagName("track").count() - 1;
3928     QDomNode track = doc.elementsByTagName("track").at(ix);
3929     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
3930     QDomNodeList transitions = doc.elementsByTagName("transition");
3931     for (int i = 0; i < transitions.count(); i++) {
3932         QDomElement e = transitions.at(i).toElement();
3933         QDomNodeList props = e.elementsByTagName("property");
3934         QMap <QString, QString> mappedProps;
3935         for (int j = 0; j < props.count(); j++) {
3936             QDomElement f = props.at(j).toElement();
3937             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
3938         }
3939         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
3940             tractor.removeChild(transitions.at(i));
3941             i--;
3942         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
3943             // Transition needs to be moved
3944             int a_track = mappedProps.value("a_track").toInt();
3945             int b_track = mappedProps.value("b_track").toInt();
3946             if (a_track > 0 && a_track >= ix) a_track --;
3947             if (b_track == ix) {
3948                 // transition was on the deleted track, so remove it
3949                 tractor.removeChild(transitions.at(i));
3950                 i--;
3951                 continue;
3952             }
3953             if (b_track > 0 && b_track > ix) b_track --;
3954             for (int j = 0; j < props.count(); j++) {
3955                 QDomElement f = props.at(j).toElement();
3956                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
3957                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
3958             }
3959
3960         }
3961     }
3962     tractor.removeChild(track);
3963     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
3964     setSceneList(doc.toString(), m_mltConsumer->position());
3965     emit refreshDocumentProducers(false, false);
3966 }
3967
3968
3969 void Render::updatePreviewSettings()
3970 {
3971     kDebug() << "////// RESTARTING CONSUMER";
3972     if (!m_mltConsumer || !m_mltProducer) return;
3973     if (m_mltProducer->get_playtime() == 0) return;
3974     Mlt::Service service(m_mltProducer->parent().get_service());
3975     if (service.type() != tractor_type) return;
3976
3977     //m_mltConsumer->set("refresh", 0);
3978     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
3979     m_mltConsumer->purge();
3980     QString scene = sceneList();
3981     int pos = 0;
3982     if (m_mltProducer) {
3983         pos = m_mltProducer->position();
3984     }
3985
3986     setSceneList(scene, pos);
3987 }
3988
3989
3990 QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
3991 {
3992     // Update all frame positions to the new fps value
3993     //WARNING: there are probably some effects or other that hold a frame value
3994     // as parameter and will also need to be updated here!
3995     QDomDocument doc;
3996     doc.setContent(scene);
3997
3998     double factor = new_fps / current_fps;
3999     QDomNodeList producers = doc.elementsByTagName("producer");
4000     for (int i = 0; i < producers.count(); i++) {
4001         QDomElement prod = producers.at(i).toElement();
4002         prod.removeAttribute("in");
4003         prod.removeAttribute("out");
4004
4005         QDomNodeList props = prod.childNodes();
4006         for (int j = 0; j < props.count(); j++) {
4007             QDomElement param =  props.at(j).toElement();
4008             QString paramName = param.attribute("name");
4009             if (paramName.startsWith("meta.") || paramName == "length") {
4010                 prod.removeChild(props.at(j));
4011                 j--;
4012             }
4013         }
4014     }
4015
4016     QDomNodeList entries = doc.elementsByTagName("entry");
4017     for (int i = 0; i < entries.count(); i++) {
4018         QDomElement entry = entries.at(i).toElement();
4019         int in = entry.attribute("in").toInt();
4020         int out = entry.attribute("out").toInt();
4021         in = factor * in + 0.5;
4022         out = factor * out + 0.5;
4023         entry.setAttribute("in", in);
4024         entry.setAttribute("out", out);
4025     }
4026
4027     QDomNodeList blanks = doc.elementsByTagName("blank");
4028     for (int i = 0; i < blanks.count(); i++) {
4029         QDomElement blank = blanks.at(i).toElement();
4030         int length = blank.attribute("length").toInt();
4031         length = factor * length + 0.5;
4032         blank.setAttribute("length", QString::number(length));
4033     }
4034
4035     QDomNodeList filters = doc.elementsByTagName("filter");
4036     for (int i = 0; i < filters.count(); i++) {
4037         QDomElement filter = filters.at(i).toElement();
4038         int in = filter.attribute("in").toInt();
4039         int out = filter.attribute("out").toInt();
4040         in = factor * in + 0.5;
4041         out = factor * out + 0.5;
4042         filter.setAttribute("in", in);
4043         filter.setAttribute("out", out);
4044     }
4045
4046     QDomNodeList transitions = doc.elementsByTagName("transition");
4047     for (int i = 0; i < transitions.count(); i++) {
4048         QDomElement transition = transitions.at(i).toElement();
4049         int in = transition.attribute("in").toInt();
4050         int out = transition.attribute("out").toInt();
4051         in = factor * in + 0.5;
4052         out = factor * out + 0.5;
4053         transition.setAttribute("in", in);
4054         transition.setAttribute("out", out);
4055         QDomNodeList props = transition.childNodes();
4056         for (int j = 0; j < props.count(); j++) {
4057             QDomElement param =  props.at(j).toElement();
4058             QString paramName = param.attribute("name");
4059             if (paramName == "geometry") {
4060                 QString geom = param.firstChild().nodeValue();
4061                 QStringList keys = geom.split(';');
4062                 QStringList newKeys;
4063                 for (int k = 0; k < keys.size(); ++k) {
4064                     if (keys.at(k).contains('=')) {
4065                         int pos = keys.at(k).section('=', 0, 0).toInt();
4066                         pos = factor * pos + 0.5;
4067                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4068                     } else newKeys.append(keys.at(k));
4069                 }
4070                 param.firstChild().setNodeValue(newKeys.join(";"));
4071             }
4072         }
4073     }
4074     QDomElement tractor = doc.elementsByTagName("tractor").at(0).toElement();
4075     int out = tractor.attribute("out").toInt();
4076     out = factor * out + 0.5;
4077     tractor.setAttribute("out", out);
4078     emit durationChanged(out);
4079
4080     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4081     return doc.toString();
4082 }
4083
4084
4085 void Render::sendFrameUpdate()
4086 {
4087     if (m_mltProducer) {
4088         Mlt::Frame * frame = m_mltProducer->get_frame();
4089         emitFrameUpdated(*frame);
4090         delete frame;
4091     }
4092 }
4093
4094 Mlt::Producer* Render::getProducer()
4095 {
4096     return m_mltProducer;
4097 }
4098
4099
4100 #include "renderer.moc"
4101