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