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