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