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