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