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