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