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