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