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