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