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