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