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