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