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