]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Merge branch 'master' of git://anongit.kde.org/kdenlive
[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             if (af > 0) filePropertyMap["frequency"] = QString::number(af);
994             if (ac > 0) 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) {
1566         m_mltConsumer->set("refresh", 0);
1567         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1568         m_mltConsumer->purge();
1569     }
1570
1571     if (m_mltProducer) {
1572         if (m_isZoneMode) resetZoneMode();
1573         m_mltProducer->set_speed(0.0);
1574     }
1575 }
1576
1577 void Render::stop(const GenTime & startTime)
1578 {
1579     requestedSeekPosition = SEEK_INACTIVE;
1580     m_refreshTimer.stop();
1581     QMutexLocker locker(&m_mutex);
1582     if (m_mltProducer) {
1583         if (m_isZoneMode) resetZoneMode();
1584         m_mltProducer->set_speed(0.0);
1585         m_mltProducer->seek((int) startTime.frames(m_fps));
1586     }
1587     m_mltConsumer->purge();
1588 }
1589
1590 void Render::pause()
1591 {
1592     requestedSeekPosition = SEEK_INACTIVE;
1593     if (!m_mltProducer || !m_mltConsumer)
1594         return;
1595     m_paused = true;
1596     m_mltProducer->set_speed(0.0);
1597     /*m_mltConsumer->set("refresh", 0);
1598     //if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1599     m_mltProducer->seek(m_mltConsumer->position());*/
1600 }
1601
1602 void Render::switchPlay(bool play)
1603 {
1604     QMutexLocker locker(&m_mutex);
1605     requestedSeekPosition = SEEK_INACTIVE;
1606     if (!m_mltProducer || !m_mltConsumer)
1607         return;
1608     if (m_isZoneMode) resetZoneMode();
1609     if (play && m_paused) {
1610         if (m_name == Kdenlive::clipMonitor && m_mltConsumer->position() == m_mltProducer->get_out()) m_mltProducer->seek(0);
1611         m_paused = false;
1612         m_mltProducer->set_speed(1.0);
1613         if (m_mltConsumer->is_stopped()) {
1614             m_mltConsumer->start();
1615         }
1616         m_mltConsumer->set("refresh", 1);
1617     } else if (!play) {
1618         m_paused = true;
1619         m_mltProducer->set_speed(0.0);
1620     }
1621 }
1622
1623 void Render::play(double speed)
1624 {
1625     requestedSeekPosition = SEEK_INACTIVE;
1626     if (!m_mltProducer) return;
1627     double current_speed = m_mltProducer->get_speed();
1628     if (current_speed == speed) return;
1629     if (m_isZoneMode) resetZoneMode();
1630     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1631     m_mltProducer->set_speed(speed);
1632     if (m_mltConsumer->is_stopped() && speed != 0) {
1633         m_mltConsumer->start();
1634     }
1635     m_paused = speed == 0;
1636     if (current_speed == 0 && speed != 0) m_mltConsumer->set("refresh", 1);
1637 }
1638
1639 void Render::play(const GenTime & startTime)
1640 {
1641     requestedSeekPosition = SEEK_INACTIVE;
1642     if (!m_mltProducer || !m_mltConsumer)
1643         return;
1644     m_paused = false;
1645     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1646     m_mltProducer->set_speed(1.0);
1647     m_mltConsumer->set("refresh", 1);
1648 }
1649
1650 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime)
1651 {
1652     requestedSeekPosition = SEEK_INACTIVE;
1653     if (!m_mltProducer || !m_mltConsumer)
1654         return;
1655     //m_mltProducer->set("eof", "loop");
1656     m_isLoopMode = true;
1657     m_loopStart = startTime;
1658     playZone(startTime, stopTime);
1659 }
1660
1661 void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
1662 {
1663     requestedSeekPosition = SEEK_INACTIVE;
1664     if (!m_mltProducer || !m_mltConsumer)
1665         return; 
1666     m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
1667     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1668     m_paused = false;
1669     m_mltProducer->set_speed(1.0);
1670     if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1671     m_mltConsumer->set("refresh", 1);
1672     m_isZoneMode = true;
1673 }
1674
1675 void Render::resetZoneMode()
1676 {
1677     if (!m_isZoneMode && !m_isLoopMode) return;
1678     m_mltProducer->set("out", m_mltProducer->get_length());
1679     m_isZoneMode = false;
1680     m_isLoopMode = false;
1681 }
1682
1683 void Render::seekToFrame(int pos)
1684 {
1685     if (!m_mltProducer)
1686         return;
1687     resetZoneMode();
1688     seek(pos);
1689 }
1690
1691 void Render::seekToFrameDiff(int diff)
1692 {
1693     if (!m_mltProducer)
1694         return;
1695     resetZoneMode();
1696     if (requestedSeekPosition == SEEK_INACTIVE)
1697         seek(m_mltProducer->position() + diff);
1698     else seek(requestedSeekPosition + diff);
1699 }
1700
1701 void Render::refreshIfActive()
1702 {
1703     if (!m_mltConsumer->is_stopped() && m_mltProducer && m_paused) m_refreshTimer.start();
1704 }
1705
1706 void Render::doRefresh()
1707 {
1708     if (m_mltProducer && m_paused) m_refreshTimer.start();
1709 }
1710
1711 void Render::refresh()
1712 {
1713     m_refreshTimer.stop();
1714     QMutexLocker locker(&m_mutex);
1715     if (!m_mltProducer)
1716         return;
1717     if (m_mltConsumer) {
1718         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1719         m_mltConsumer->set("refresh", 1);
1720         //m_mltConsumer->purge();
1721     }
1722 }
1723
1724 void Render::setDropFrames(bool show)
1725 {
1726     QMutexLocker locker(&m_mutex);
1727     if (m_mltConsumer) {
1728         int dropFrames = KdenliveSettings::mltthreads();
1729         if (show == false) dropFrames = -dropFrames;
1730         m_mltConsumer->stop();
1731         if (m_winid == 0)
1732             m_mltConsumer->set("real_time", dropFrames);
1733         else
1734             m_mltConsumer->set("play.real_time", dropFrames);
1735
1736         if (m_mltConsumer->start() == -1) {
1737             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1738         }
1739
1740     }
1741 }
1742
1743 bool Render::isPlaying() const
1744 {
1745     if (!m_mltConsumer || m_mltConsumer->is_stopped()) return false;
1746     return !m_paused;
1747 }
1748
1749 double Render::playSpeed() const
1750 {
1751     if (m_mltProducer) return m_mltProducer->get_speed();
1752     return 0.0;
1753 }
1754
1755 GenTime Render::seekPosition() const
1756 {
1757     if (m_mltConsumer) return GenTime((int) m_mltConsumer->position(), m_fps);
1758     //if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1759     else return GenTime();
1760 }
1761
1762 int Render::seekFramePosition() const
1763 {
1764     //if (m_mltProducer) return (int) m_mltProducer->position();
1765     if (m_mltConsumer) return (int) m_mltConsumer->position();
1766     return 0;
1767 }
1768
1769 void Render::emitFrameUpdated(Mlt::Frame& frame)
1770 {
1771     mlt_image_format format = mlt_image_rgb24a;
1772     int width = 0;
1773     int height = 0;
1774     const uchar* image = frame.get_image(format, width, height);
1775     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1776     memcpy(qimage.scanLine(0), image, width * height * 4);
1777     emit frameUpdated(qimage.rgbSwapped());
1778 }
1779
1780 int Render::getCurrentSeekPosition() const
1781 {
1782     if (requestedSeekPosition != SEEK_INACTIVE) return requestedSeekPosition;
1783     return (int) m_mltProducer->position();
1784 }
1785
1786 void Render::emitFrameNumber()
1787 {
1788     int currentPos = m_mltConsumer->position();
1789     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1790     emit rendererPosition(currentPos);
1791     if (requestedSeekPosition != SEEK_INACTIVE) {
1792         m_mltConsumer->purge();
1793         m_mltProducer->seek(requestedSeekPosition);
1794         if (m_mltProducer->get_speed() == 0 && m_paused) {
1795             m_paused = false;
1796             m_mltConsumer->set("refresh", 1);
1797         }
1798         requestedSeekPosition = SEEK_INACTIVE;
1799     }
1800 }
1801
1802 void Render::emitConsumerStopped(bool forcePause)
1803 {
1804     // This is used to know when the playing stopped
1805     if (m_mltProducer && (forcePause || (!m_paused && m_mltProducer->get_speed() == 0))) {
1806         double pos = m_mltProducer->position();
1807         m_paused = true;
1808         if (m_isLoopMode) play(m_loopStart);
1809         //else if (m_isZoneMode) resetZoneMode();
1810         emit rendererStopped((int) pos);
1811     }
1812 }
1813
1814 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1815 {
1816     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1817 }
1818
1819 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
1820 {
1821     if (!m_mltProducer) {
1822         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1823         return;
1824     }
1825
1826     //int height = 1080;//KdenliveSettings::defaultheight();
1827     //int width = 1940; //KdenliveSettings::displaywidth();
1828     //TODO: rewrite
1829     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1830     /*
1831        QPixmap pix(width, height);
1832        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1833        m_convert.set("forced", mlt_image_rgb24a);
1834        m_mltProducer->attach(m_convert);
1835        Mlt::Frame * frame = m_mltProducer->get_frame();
1836        m_mltProducer->detach(m_convert);
1837        if (frame) {
1838            pix = frameThumbnail(frame, width, height);
1839            delete frame;
1840        }*/
1841     pix.save(url.path(), "PNG");
1842     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1843 }
1844
1845
1846 void Render::showFrame(Mlt::Frame* frame)
1847 {
1848     int currentPos = m_mltConsumer->position();
1849     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1850     emit rendererPosition(currentPos);
1851     if (frame->is_valid()) {
1852         mlt_image_format format = mlt_image_rgb24a;
1853         int width = 0;
1854         int height = 0;
1855         const uchar* image = frame->get_image(format, width, height);
1856         QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1857         memcpy(qimage.scanLine(0), image, width * height * 4);
1858         if (analyseAudio) showAudio(*frame);
1859         delete frame;
1860         emit showImageSignal(qimage);
1861         if (sendFrameForAnalysis) {
1862             emit frameUpdated(qimage.rgbSwapped());
1863         }
1864     } else delete frame;
1865     showFrameSemaphore.release();
1866     emit checkSeeking();
1867 }
1868
1869 void Render::slotCheckSeeking()
1870 {
1871       if (requestedSeekPosition != SEEK_INACTIVE) {
1872         m_mltProducer->seek(requestedSeekPosition);
1873         if (m_paused) {
1874             refresh();
1875         }
1876         requestedSeekPosition = SEEK_INACTIVE;
1877     }
1878 }
1879
1880 void Render::disablePreview(bool disable)
1881 {
1882     if (m_mltConsumer) {
1883         m_mltConsumer->stop();
1884         m_mltConsumer->set("preview_off", (int) disable);
1885         m_mltConsumer->set("refresh", 0);
1886         m_mltConsumer->start();
1887     }
1888 }
1889
1890 void Render::showAudio(Mlt::Frame& frame)
1891 {
1892     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1893         return;
1894     }
1895
1896     mlt_audio_format audio_format = mlt_audio_s16;
1897     //FIXME: should not be hardcoded..
1898     int freq = 48000;
1899     int num_channels = 2;
1900     int samples = 0;
1901     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1902
1903     if (!data) {
1904         return;
1905     }
1906
1907     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1908     // So the vector is of size samples*channels.
1909     QVector<int16_t> sampleVector(samples*num_channels);
1910     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1911
1912     if (samples > 0) {
1913         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1914     }
1915 }
1916
1917 /*
1918  * MLT playlist direct manipulation.
1919  */
1920
1921 void Render::mltCheckLength(Mlt::Tractor *tractor)
1922 {
1923     //kDebug()<<"checking track length: "<<track<<"..........";
1924
1925     int trackNb = tractor->count();
1926     int duration = 0;
1927     int trackDuration;
1928     if (m_isZoneMode) resetZoneMode();
1929     if (trackNb == 1) {
1930         Mlt::Producer trackProducer(tractor->track(0));
1931         duration = trackProducer.get_playtime() - 1;
1932         m_mltProducer->set("out", duration);
1933         emit durationChanged(duration);
1934         return;
1935     }
1936     while (trackNb > 1) {
1937         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1938         trackDuration = trackProducer.get_playtime() - 1;
1939         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1940         if (trackDuration > duration) duration = trackDuration;
1941         trackNb--;
1942     }
1943
1944     Mlt::Producer blackTrackProducer(tractor->track(0));
1945
1946     if (blackTrackProducer.get_playtime() - 1 != duration) {
1947         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1948         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1949         if (blackclip && blackclip->is_blank()) {
1950             delete blackclip;
1951             blackclip = NULL;
1952         }
1953
1954         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
1955             if (blackclip) delete blackclip;
1956             blackTrackPlaylist.clear();
1957             m_blackClip->set("length", duration + 1);
1958             m_blackClip->set("out", duration);
1959             blackclip = m_blackClip->cut(0, duration);
1960             blackTrackPlaylist.insert_at(0, blackclip, 1);
1961         } else {
1962             if (duration > blackclip->parent().get_length()) {
1963                 blackclip->parent().set("length", duration + 1);
1964                 blackclip->parent().set("out", duration);
1965                 blackclip->set("length", duration + 1);
1966             }
1967             blackTrackPlaylist.resize_clip(0, 0, duration);
1968         }
1969
1970         delete blackclip;
1971         if (m_mltConsumer->position() > duration) {
1972             m_mltConsumer->purge();
1973             m_mltProducer->seek(duration);
1974         }
1975         m_mltProducer->set("out", duration);
1976         emit durationChanged(duration);
1977     }
1978 }
1979
1980 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
1981 {
1982     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
1983     QLocale locale;
1984     // We want a slowmotion producer
1985     double speed = element.attribute("speed", "1.0").toDouble();
1986     int strobe = element.attribute("strobe", "1").toInt();
1987     QString url = QString::fromUtf8(prod->get("resource"));
1988     url.append('?' + locale.toString(speed));
1989     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
1990     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1991     if (!slowprod || slowprod->get_producer() == NULL) {
1992         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
1993         if (strobe > 1) slowprod->set("strobe", strobe);
1994         QString id = prod->parent().get("id");
1995         if (id.contains('_')) id = id.section('_', 0, 0);
1996         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
1997         if (strobe > 1) producerid.append(':' + QString::number(strobe));
1998         slowprod->set("id", producerid.toUtf8().constData());
1999         m_slowmotionProducers.insert(url, slowprod);
2000     }
2001     return slowprod;
2002 }
2003
2004 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
2005 {
2006     m_refreshTimer.stop();
2007     if (m_mltProducer == NULL) {
2008         kDebug() << "PLAYLIST NOT INITIALISED //////";
2009         return -1;
2010     }
2011     if (prod == NULL) {
2012         kDebug() << "Cannot insert clip without producer //////";
2013         return -1;
2014     }
2015     Mlt::Producer parentProd(m_mltProducer->parent());
2016     if (parentProd.get_producer() == NULL) {
2017         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2018         return -1;
2019     }
2020
2021     Mlt::Service service(parentProd.get_service());
2022     if (service.type() != tractor_type) {
2023         kWarning() << "// TRACTOR PROBLEM";
2024         return -1;
2025     }
2026     Mlt::Tractor tractor(service);
2027     if (info.track > tractor.count() - 1) {
2028         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
2029         return -1;
2030     }
2031     service.lock();
2032     Mlt::Producer trackProducer(tractor.track(info.track));
2033     int trackDuration = trackProducer.get_playtime() - 1;
2034     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2035     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
2036     prod = checkSlowMotionProducer(prod, element);
2037     if (prod == NULL || !prod->is_valid()) {
2038         service.unlock();
2039         return -1;
2040     }
2041
2042     int cutPos = (int) info.cropStart.frames(m_fps);
2043     if (cutPos < 0) cutPos = 0;
2044     int insertPos = (int) info.startPos.frames(m_fps);
2045     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
2046     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
2047     if (overwrite && (insertPos < trackDuration)) {
2048         // Replace zone with blanks
2049         //trackPlaylist.split_at(insertPos, true);
2050         trackPlaylist.remove_region(insertPos, cutDuration + 1);
2051         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2052         trackPlaylist.insert_blank(clipIndex, cutDuration);
2053     } else if (push) {
2054         trackPlaylist.split_at(insertPos, true);
2055         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2056         trackPlaylist.insert_blank(clipIndex, cutDuration);
2057     }
2058     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
2059     delete clip;
2060     /*if (QString(prod->get("transparency")).toInt() == 1)
2061         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
2062
2063     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
2064     service.unlock();
2065     /*tractor.multitrack()->refresh();
2066     tractor.refresh();*/
2067     return 0;
2068 }
2069
2070
2071 bool Render::mltCutClip(int track, GenTime position)
2072 {
2073     Mlt::Service service(m_mltProducer->parent().get_service());
2074     if (service.type() != tractor_type) {
2075         kWarning() << "// TRACTOR PROBLEM";
2076         return false;
2077     }
2078
2079     Mlt::Tractor tractor(service);
2080     Mlt::Producer trackProducer(tractor.track(track));
2081     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2082
2083
2084     /* // Display playlist info
2085     kDebug()<<"////////////  BEFORE";
2086     for (int i = 0; i < trackPlaylist.count(); i++) {
2087     int blankStart = trackPlaylist.clip_start(i);
2088     int blankDuration = trackPlaylist.clip_length(i) - 1;
2089     QString blk;
2090     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2091     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2092     }*/
2093
2094     int cutPos = (int) position.frames(m_fps);
2095
2096     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
2097     if (trackPlaylist.is_blank(clipIndex)) {
2098         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
2099         return false;
2100     }
2101     service.lock();
2102     int clipStart = trackPlaylist.clip_start(clipIndex);
2103     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
2104     service.unlock();
2105
2106     // duplicate effects
2107     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
2108     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
2109     
2110     if (original == NULL || clip == NULL) {
2111         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
2112         return false;
2113     }
2114
2115     Mlt::Service clipService(original->get_service());
2116     Mlt::Service dupService(clip->get_service());
2117
2118
2119     delete original;
2120     delete clip;
2121     int ct = 0;
2122     Mlt::Filter *filter = clipService.filter(ct);
2123     while (filter) {
2124         // Only duplicate Kdenlive filters, and skip the fade in effects
2125         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
2126             // looks like there is no easy way to duplicate a filter,
2127             // so we will create a new one and duplicate its properties
2128             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
2129             if (dup && dup->is_valid()) {
2130                 Mlt::Properties entries(filter->get_properties());
2131                 for (int i = 0; i < entries.count(); i++) {
2132                     dup->set(entries.get_name(i), entries.get(i));
2133                 }
2134                 dupService.attach(*dup);
2135             }
2136         }
2137         ct++;
2138         filter = clipService.filter(ct);
2139     }
2140     return true;
2141     /* // Display playlist info
2142     kDebug()<<"////////////  AFTER";
2143     for (int i = 0; i < trackPlaylist.count(); i++) {
2144     int blankStart = trackPlaylist.clip_start(i);
2145     int blankDuration = trackPlaylist.clip_length(i) - 1;
2146     QString blk;
2147     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2148     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2149     }*/
2150
2151 }
2152
2153 Mlt::Tractor *Render::lockService()
2154 {
2155     // we are going to replace some clips, purge consumer
2156     if (!m_mltProducer) return NULL;
2157     QMutexLocker locker(&m_mutex);
2158     if (m_mltConsumer) {
2159         m_mltConsumer->purge();
2160     }
2161     Mlt::Service service(m_mltProducer->parent().get_service());
2162     if (service.type() != tractor_type) {
2163         return NULL;
2164     }
2165     service.lock();
2166     return new Mlt::Tractor(service);
2167
2168 }
2169
2170 void Render::unlockService(Mlt::Tractor *tractor)
2171 {
2172     if (tractor) {
2173         delete tractor;
2174     }
2175     if (!m_mltProducer) return;
2176     Mlt::Service service(m_mltProducer->parent().get_service());
2177     if (service.type() != tractor_type) {
2178         kWarning() << "// TRACTOR PROBLEM";
2179         return;
2180     }
2181     service.unlock();
2182 }
2183
2184 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
2185 {
2186     // TODO: optimize
2187     if (prod == NULL || tractor == NULL) {
2188         kDebug() << "Cannot update clip with null producer //////";
2189         return false;
2190     }
2191
2192     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
2193     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2194     int startPos = info.startPos.frames(m_fps);
2195     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2196     if (trackPlaylist.is_blank(clipIndex)) {
2197         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
2198         return false;
2199     }
2200     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2201     // keep effects
2202     QList <Mlt::Filter *> filtersList;
2203     Mlt::Service sourceService(clip->get_service());
2204     int ct = 0;
2205     Mlt::Filter *filter = sourceService.filter(ct);
2206     while (filter) {
2207         if (filter->get_int("kdenlive_ix") != 0) {
2208             filtersList.append(filter);
2209         }
2210         ct++;
2211         filter = sourceService.filter(ct);
2212     }
2213     delete clip;
2214     clip = trackPlaylist.replace_with_blank(clipIndex);
2215     delete clip;
2216     prod = checkSlowMotionProducer(prod, element);
2217     if (prod == NULL || !prod->is_valid()) {
2218         return false;
2219     }
2220
2221     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
2222     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
2223     Mlt::Service destService(clip2->get_service());
2224     delete clip2;
2225
2226     if (!filtersList.isEmpty()) {
2227         for (int i = 0; i < filtersList.count(); i++)
2228             destService.attach(*(filtersList.at(i)));
2229     }
2230     return true;
2231 }
2232
2233
2234 bool Render::mltRemoveClip(int track, GenTime position)
2235 {
2236     m_refreshTimer.stop();
2237     Mlt::Service service(m_mltProducer->parent().get_service());
2238     if (service.type() != tractor_type) {
2239         kWarning() << "// TRACTOR PROBLEM";
2240         return false;
2241     }
2242     //service.lock();
2243     Mlt::Tractor tractor(service);
2244     Mlt::Producer trackProducer(tractor.track(track));
2245     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2246     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2247
2248     if (trackPlaylist.is_blank(clipIndex)) {
2249         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
2250         //service.unlock();
2251         return false;
2252     }
2253     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2254     if (clip) delete clip;
2255     trackPlaylist.consolidate_blanks(0);
2256
2257     /* // Display playlist info
2258     kDebug()<<"////  AFTER";
2259     for (int i = 0; i < trackPlaylist.count(); i++) {
2260     int blankStart = trackPlaylist.clip_start(i);
2261     int blankDuration = trackPlaylist.clip_length(i) - 1;
2262     QString blk;
2263     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2264     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2265     }*/
2266     //service.unlock();
2267     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
2268     return true;
2269 }
2270
2271 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
2272 {
2273     if (!m_mltProducer) {
2274         kDebug() << "PLAYLIST NOT INITIALISED //////";
2275         return 0;
2276     }
2277     Mlt::Producer parentProd(m_mltProducer->parent());
2278     if (parentProd.get_producer() == NULL) {
2279         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2280         return 0;
2281     }
2282
2283     Mlt::Service service(parentProd.get_service());
2284     Mlt::Tractor tractor(service);
2285     int insertPos = pos.frames(m_fps);
2286
2287     Mlt::Producer trackProducer(tractor.track(track));
2288     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2289     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2290     if (clipIndex == trackPlaylist.count()) {
2291         // We are after the end of the playlist
2292         return -1;
2293     }
2294     if (!trackPlaylist.is_blank(clipIndex)) return 0;
2295     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
2296     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
2297 }
2298
2299 int Render::mltTrackDuration(int track)
2300 {
2301     if (!m_mltProducer) {
2302         kDebug() << "PLAYLIST NOT INITIALISED //////";
2303         return -1;
2304     }
2305     Mlt::Producer parentProd(m_mltProducer->parent());
2306     if (parentProd.get_producer() == NULL) {
2307         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2308         return -1;
2309     }
2310
2311     Mlt::Service service(parentProd.get_service());
2312     Mlt::Tractor tractor(service);
2313
2314     Mlt::Producer trackProducer(tractor.track(track));
2315     return trackProducer.get_playtime() - 1;
2316 }
2317
2318 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
2319 {
2320     if (!m_mltProducer) {
2321         kDebug() << "PLAYLIST NOT INITIALISED //////";
2322         return;
2323     }
2324     Mlt::Producer parentProd(m_mltProducer->parent());
2325     if (parentProd.get_producer() == NULL) {
2326         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2327         return;
2328     }
2329     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
2330     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
2331
2332     Mlt::Service service(parentProd.get_service());
2333     Mlt::Tractor tractor(service);
2334     service.lock();
2335     int diff = duration.frames(m_fps);
2336     int offset = timeOffset.frames(m_fps);
2337     int insertPos;
2338
2339     if (track != -1) {
2340         // insert space in one track only
2341         Mlt::Producer trackProducer(tractor.track(track));
2342         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2343         insertPos = trackClipStartList.value(track);
2344         if (insertPos != -1) {
2345             insertPos += offset;
2346             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2347             if (diff > 0) {
2348                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2349             } else {
2350                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2351                 if (!trackPlaylist.is_blank(clipIndex)) {
2352                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2353                 }
2354                 int position = trackPlaylist.clip_start(clipIndex);
2355                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2356                 if (blankDuration + diff == 0) {
2357                     trackPlaylist.remove(clipIndex);
2358                 } else trackPlaylist.remove_region(position, -diff);
2359             }
2360             trackPlaylist.consolidate_blanks(0);
2361         }
2362         // now move transitions
2363         mlt_service serv = m_mltProducer->parent().get_service();
2364         mlt_service nextservice = mlt_service_get_producer(serv);
2365         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2366         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2367         QString resource = mlt_properties_get(properties, "mlt_service");
2368
2369         while (mlt_type == "transition") {
2370             mlt_transition tr = (mlt_transition) nextservice;
2371             int currentTrack = mlt_transition_get_b_track(tr);
2372             int currentIn = (int) mlt_transition_get_in(tr);
2373             int currentOut = (int) mlt_transition_get_out(tr);
2374             insertPos = trackTransitionStartList.value(track);
2375             if (insertPos != -1) {
2376                 insertPos += offset;
2377                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2378                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2379                 }
2380             }
2381             nextservice = mlt_service_producer(nextservice);
2382             if (nextservice == NULL) break;
2383             properties = MLT_SERVICE_PROPERTIES(nextservice);
2384             mlt_type = mlt_properties_get(properties, "mlt_type");
2385             resource = mlt_properties_get(properties, "mlt_service");
2386         }
2387     } else {
2388         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2389             Mlt::Producer trackProducer(tractor.track(trackNb));
2390             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2391
2392             //int clipNb = trackPlaylist.count();
2393             insertPos = trackClipStartList.value(trackNb);
2394             if (insertPos != -1) {
2395                 insertPos += offset;
2396
2397                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2398                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2399                         for (int i = 0; i < clipNb; i++) {
2400                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2401                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2402                      kDebug()<<"-------------";
2403                  }
2404                  kDebug()<<"END-------------";*/
2405
2406
2407                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2408                 if (diff > 0) {
2409                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2410                 } else {
2411                     if (!trackPlaylist.is_blank(clipIndex)) {
2412                         clipIndex --;
2413                     }
2414                     if (!trackPlaylist.is_blank(clipIndex)) {
2415                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2416                     }
2417                     int position = trackPlaylist.clip_start(clipIndex);
2418                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2419                     if (diff + blankDuration == 0) {
2420                         trackPlaylist.remove(clipIndex);
2421                     } else trackPlaylist.remove_region(position, - diff);
2422                 }
2423                 trackPlaylist.consolidate_blanks(0);
2424             }
2425         }
2426         // now move transitions
2427         mlt_service serv = m_mltProducer->parent().get_service();
2428         mlt_service nextservice = mlt_service_get_producer(serv);
2429         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2430         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2431         QString resource = mlt_properties_get(properties, "mlt_service");
2432
2433         while (mlt_type == "transition") {
2434             mlt_transition tr = (mlt_transition) nextservice;
2435             int currentIn = (int) mlt_transition_get_in(tr);
2436             int currentOut = (int) mlt_transition_get_out(tr);
2437             int currentTrack = mlt_transition_get_b_track(tr);
2438             insertPos = trackTransitionStartList.value(currentTrack);
2439             if (insertPos != -1) {
2440                 insertPos += offset;
2441                 if (currentOut > insertPos && resource != "mix") {
2442                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2443                 }
2444             }
2445             nextservice = mlt_service_producer(nextservice);
2446             if (nextservice == NULL) break;
2447             properties = MLT_SERVICE_PROPERTIES(nextservice);
2448             mlt_type = mlt_properties_get(properties, "mlt_type");
2449             resource = mlt_properties_get(properties, "mlt_service");
2450         }
2451     }
2452     service.unlock();
2453     mltCheckLength(&tractor);
2454     m_mltConsumer->set("refresh", 1);
2455 }
2456
2457
2458 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2459 {
2460     if (source == dest) return;
2461     Mlt::Service sourceService(source->get_service());
2462     Mlt::Service destService(dest->get_service());
2463
2464     // move all effects to the correct producer
2465     int ct = 0;
2466     Mlt::Filter *filter = sourceService.filter(ct);
2467     while (filter) {
2468         if (filter->get_int("kdenlive_ix") != 0) {
2469             sourceService.detach(*filter);
2470             destService.attach(*filter);
2471         } else ct++;
2472         filter = sourceService.filter(ct);
2473     }
2474 }
2475
2476 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2477 {
2478     int newLength = 0;
2479     Mlt::Service service(m_mltProducer->parent().get_service());
2480     if (service.type() != tractor_type) {
2481         kWarning() << "// TRACTOR PROBLEM";
2482         return -1;
2483     }
2484
2485     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2486     Mlt::Tractor tractor(service);
2487     Mlt::Producer trackProducer(tractor.track(info.track));
2488     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2489     int startPos = info.startPos.frames(m_fps);
2490     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2491     int clipLength = trackPlaylist.clip_length(clipIndex);
2492
2493     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2494     if (original == NULL) {
2495         return -1;
2496     }
2497     if (!original->is_valid() || original->is_blank()) {
2498         // invalid clip
2499         delete original;
2500         return -1;
2501     }
2502     Mlt::Producer clipparent = original->parent();
2503     if (!clipparent.is_valid() || clipparent.is_blank()) {
2504         // invalid clip
2505         delete original;
2506         return -1;
2507     }
2508
2509     QString serv = clipparent.get("mlt_service");
2510     QString id = clipparent.get("id");
2511     if (speed <= 0 && speed > -1) speed = 1.0;
2512     //kDebug() << "CLIP SERVICE: " << serv;
2513     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2514         service.lock();
2515         QString url = QString::fromUtf8(clipparent.get("resource"));
2516         url.append('?' + m_locale.toString(speed));
2517         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2518         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2519         if (!slowprod || slowprod->get_producer() == NULL) {
2520             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2521             if (strobe > 1) slowprod->set("strobe", strobe);
2522             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2523             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2524             slowprod->set("id", producerid.toUtf8().constData());
2525             // copy producer props
2526             double ar = original->parent().get_double("force_aspect_ratio");
2527             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2528             double fps = original->parent().get_double("force_fps");
2529             if (fps != 0.0) slowprod->set("force_fps", fps);
2530             int threads = original->parent().get_int("threads");
2531             if (threads != 0) slowprod->set("threads", threads);
2532             if (original->parent().get("force_progressive"))
2533                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2534             if (original->parent().get("force_tff"))
2535                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2536             int ix = original->parent().get_int("video_index");
2537             if (ix != 0) slowprod->set("video_index", ix);
2538             int colorspace = original->parent().get_int("force_colorspace");
2539             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2540             int full_luma = original->parent().get_int("set.force_full_luma");
2541             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2542             m_slowmotionProducers.insert(url, slowprod);
2543         }
2544         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2545         trackPlaylist.consolidate_blanks(0);
2546
2547         // Check that the blank space is long enough for our new duration
2548         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2549         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2550         Mlt::Producer *cut;
2551         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2552             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2553             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2554         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2555
2556         // move all effects to the correct producer
2557         mltPasteEffects(clip, cut);
2558         trackPlaylist.insert_at(startPos, cut, 1);
2559         delete cut;
2560         delete clip;
2561         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2562         newLength = trackPlaylist.clip_length(clipIndex);
2563         service.unlock();
2564     } else if (speed == 1.0 && strobe < 2) {
2565         service.lock();
2566
2567         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2568         trackPlaylist.consolidate_blanks(0);
2569
2570         // Check that the blank space is long enough for our new duration
2571         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2572         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2573
2574         Mlt::Producer *cut;
2575         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2576         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2577             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2578             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2579         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2580
2581         // move all effects to the correct producer
2582         mltPasteEffects(clip, cut);
2583
2584         trackPlaylist.insert_at(startPos, cut, 1);
2585         delete cut;
2586         delete clip;
2587         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2588         newLength = trackPlaylist.clip_length(clipIndex);
2589         service.unlock();
2590
2591     } else if (serv == "framebuffer") {
2592         service.lock();
2593         QString url = QString::fromUtf8(clipparent.get("resource"));
2594         url = url.section('?', 0, 0);
2595         url.append('?' + m_locale.toString(speed));
2596         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2597         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2598         if (!slowprod || slowprod->get_producer() == NULL) {
2599             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2600             slowprod->set("strobe", strobe);
2601             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2602             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2603             slowprod->set("id", producerid.toUtf8().constData());
2604             // copy producer props
2605             double ar = original->parent().get_double("force_aspect_ratio");
2606             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2607             double fps = original->parent().get_double("force_fps");
2608             if (fps != 0.0) slowprod->set("force_fps", fps);
2609             if (original->parent().get("force_progressive"))
2610                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2611             if (original->parent().get("force_tff"))
2612                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2613             int threads = original->parent().get_int("threads");
2614             if (threads != 0) slowprod->set("threads", threads);
2615             int ix = original->parent().get_int("video_index");
2616             if (ix != 0) slowprod->set("video_index", ix);
2617             int colorspace = original->parent().get_int("force_colorspace");
2618             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2619             int full_luma = original->parent().get_int("set.force_full_luma");
2620             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2621             m_slowmotionProducers.insert(url, slowprod);
2622         }
2623         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2624         trackPlaylist.consolidate_blanks(0);
2625
2626         GenTime duration = speedIndependantInfo.cropDuration / speed;
2627         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2628
2629         // Check that the blank space is long enough for our new duration
2630         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2631         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2632
2633         Mlt::Producer *cut;
2634         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2635             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2636             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2637         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2638
2639         // move all effects to the correct producer
2640         mltPasteEffects(clip, cut);
2641
2642         trackPlaylist.insert_at(startPos, cut, 1);
2643         delete cut;
2644         delete clip;
2645         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2646         newLength = trackPlaylist.clip_length(clipIndex);
2647
2648         service.unlock();
2649     }
2650     delete original;
2651     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2652     return newLength;
2653 }
2654
2655 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2656 {
2657     Mlt::Service service(m_mltProducer->parent().get_service());
2658     bool success = false;
2659     Mlt::Tractor tractor(service);
2660     Mlt::Producer trackProducer(tractor.track(track));
2661     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2662     Mlt::Service clipService(trackPlaylist.get_service());
2663
2664     service.lock();
2665     int ct = 0;
2666     Mlt::Filter *filter = clipService.filter(ct);
2667     while (filter) {
2668         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2669             if (clipService.detach(*filter) == 0) success = true;
2670         } else if (updateIndex) {
2671             // Adjust the other effects index
2672             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2673             ct++;
2674         } else ct++;
2675         filter = clipService.filter(ct);
2676     }
2677     service.unlock();
2678     refresh();
2679     return success;
2680 }
2681
2682 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2683 {
2684     if (position < GenTime()) {
2685         // Remove track effect
2686         return mltRemoveTrackEffect(track, index, updateIndex);
2687     }
2688     Mlt::Service service(m_mltProducer->parent().get_service());
2689     bool success = false;
2690     Mlt::Tractor tractor(service);
2691     Mlt::Producer trackProducer(tractor.track(track));
2692     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2693
2694     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2695     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2696     if (!clip) {
2697         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2698         return false;
2699     }
2700
2701     Mlt::Service clipService(clip->get_service());
2702     int duration = clip->get_playtime();
2703     if (doRefresh) {
2704         // Check if clip is visible in monitor
2705         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2706         if (diff < 0 || diff > duration) doRefresh = false;
2707     }
2708     delete clip;
2709
2710     service.lock();
2711     int ct = 0;
2712     Mlt::Filter *filter = clipService.filter(ct);
2713     while (filter) {
2714         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2715             if (clipService.detach(*filter) == 0) success = true;
2716             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2717         } else if (updateIndex) {
2718             // Adjust the other effects index
2719             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2720             ct++;
2721         } else ct++;
2722         filter = clipService.filter(ct);
2723     }
2724     service.unlock();
2725     if (doRefresh) refresh();
2726     return success;
2727 }
2728
2729 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2730 {
2731     Mlt::Service service(m_mltProducer->parent().get_service());
2732     Mlt::Tractor tractor(service);
2733     Mlt::Producer trackProducer(tractor.track(track));
2734     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2735     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2736     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2737 }
2738
2739
2740 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2741 {
2742
2743     Mlt::Service service(m_mltProducer->parent().get_service());
2744
2745     Mlt::Tractor tractor(service);
2746     Mlt::Producer trackProducer(tractor.track(track));
2747     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2748
2749     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2750     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2751     if (!clip) {
2752         return false;
2753     }
2754
2755     Mlt::Service clipService(clip->get_service());
2756     int duration = clip->get_playtime();
2757     if (doRefresh) {
2758         // Check if clip is visible in monitor
2759         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2760         if (diff < 0 || diff > duration) doRefresh = false;
2761     }
2762     delete clip;
2763     return mltAddEffect(clipService, params, duration, doRefresh);
2764 }
2765
2766 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2767 {
2768     bool updateIndex = false;
2769     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2770     int ct = 0;
2771     service.lock();
2772
2773     Mlt::Filter *filter = service.filter(ct);
2774     while (filter) {
2775         if (filter->get_int("kdenlive_ix") == filter_ix) {
2776             // A filter at that position already existed, so we will increase all indexes later
2777             updateIndex = true;
2778             break;
2779         }
2780         ct++;
2781         filter = service.filter(ct);
2782     }
2783
2784     if (params.paramValue("id") == "speed") {
2785         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2786         ct = 0;
2787         filter = service.filter(ct);
2788         while (filter) {
2789             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2790                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2791             }
2792             ct++;
2793             filter = service.filter(ct);
2794         }
2795         service.unlock();
2796         if (doRefresh) refresh();
2797         return true;
2798     }
2799
2800
2801     // temporarily remove all effects after insert point
2802     QList <Mlt::Filter *> filtersList;
2803     ct = 0;
2804     filter = service.filter(ct);
2805     while (filter) {
2806         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2807             filtersList.append(filter);
2808             service.detach(*filter);
2809         } else ct++;
2810         filter = service.filter(ct);
2811     }
2812
2813     addFilterToService(service, params, duration);
2814
2815     // re-add following filters
2816     for (int i = 0; i < filtersList.count(); i++) {
2817         Mlt::Filter *filter = filtersList.at(i);
2818         if (updateIndex)
2819             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2820         service.attach(*filter);
2821     }
2822     service.unlock();
2823     if (doRefresh) refresh();
2824     return true;
2825 }
2826
2827
2828 bool Render::addFilterToService(Mlt::Service service, EffectsParameterList params, int duration)
2829 {
2830       // create filter
2831     QString tag =  params.paramValue("tag");
2832     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2833     char *filterTag = qstrdup(tag.toUtf8().constData());
2834     char *filterId = qstrdup(params.paramValue("id").toUtf8().constData());
2835     QString kfr = params.paramValue("keyframes");
2836   if (!kfr.isEmpty()) {
2837         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2838         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2839         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2840         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2841         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2842         //double max = params.paramValue("max").toDouble();
2843         double min = params.paramValue("min").toDouble();
2844         double factor = params.paramValue("factor", "1").toDouble();
2845         double paramOffset = params.paramValue("offset", "0").toDouble();
2846         params.removeParam("starttag");
2847         params.removeParam("endtag");
2848         params.removeParam("keyframes");
2849         params.removeParam("min");
2850         params.removeParam("max");
2851         params.removeParam("factor");
2852         params.removeParam("offset");
2853         int offset = 0;
2854         // Special case, only one keyframe, means we want a constant value
2855         if (keyFrames.count() == 1) {
2856             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2857             if (filter && filter->is_valid()) {
2858                 filter->set("kdenlive_id", filterId);
2859                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2860                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2861                 for (int j = 0; j < params.count(); j++) {
2862                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2863                 }
2864                 filter->set("in", x1);
2865                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2866                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2867                 service.attach(*filter);
2868             }
2869         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2870                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2871                 if (filter && filter->is_valid()) {
2872                     filter->set("kdenlive_id", filterId);
2873                     int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2874                     double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2875                     int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2876                     double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2877                     if (x2 == -1) x2 = duration;
2878
2879                     for (int j = 0; j < params.count(); j++) {
2880                         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2881                     }
2882
2883                     filter->set("in", x1);
2884                     filter->set("out", x2);
2885                     //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2886                     filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2887                     filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2888                     service.attach(*filter);
2889                     offset = 1;
2890                 }
2891             }
2892         delete[] starttag;
2893         delete[] endtag;
2894     } else {
2895         Mlt::Filter *filter;
2896         QString prefix;
2897         filter = new Mlt::Filter(*m_mltProfile, filterTag);
2898         if (filter && filter->is_valid()) {
2899             filter->set("kdenlive_id", filterId);
2900         } else {
2901             kDebug() << "filter is NULL";
2902             service.unlock();
2903             return false;
2904         }
2905         params.removeParam("kdenlive_id");
2906         if (params.hasParam("_sync_in_out")) {
2907             // This effect must sync in / out with parent clip
2908             params.removeParam("_sync_in_out");
2909             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2910         }
2911
2912         for (int j = 0; j < params.count(); j++) {
2913             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2914         }
2915
2916         if (tag == "sox") {
2917             QString effectArgs = params.paramValue("id").section('_', 1);
2918
2919             params.removeParam("id");
2920             params.removeParam("kdenlive_ix");
2921             params.removeParam("tag");
2922             params.removeParam("disable");
2923             params.removeParam("region");
2924
2925             for (int j = 0; j < params.count(); j++) {
2926                 effectArgs.append(' ' + params.at(j).value());
2927             }
2928             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2929             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2930         }
2931         // attach filter to the clip
2932         service.attach(*filter);
2933     }
2934         
2935     delete[] filterId;
2936     delete[] filterTag;
2937     return true;
2938 }
2939
2940 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
2941 {
2942     Mlt::Service service(m_mltProducer->parent().get_service());
2943     Mlt::Tractor tractor(service);
2944     Mlt::Producer trackProducer(tractor.track(track));
2945     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2946     Mlt::Service clipService(trackPlaylist.get_service());
2947     int ct = 0;
2948     QString index = params.paramValue("kdenlive_ix");
2949     QString tag =  params.paramValue("tag");
2950
2951     Mlt::Filter *filter = clipService.filter(ct);
2952     while (filter) {
2953         if (filter->get_int("kdenlive_ix") == index.toInt()) {
2954             break;
2955         }
2956         ct++;
2957         filter = clipService.filter(ct);
2958     }
2959
2960     if (!filter) {
2961         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2962         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2963
2964         bool success = false;//mltAddTrackEffect(track, params);
2965         return success;
2966     }
2967     QString prefix;
2968     QString ser = filter->get("mlt_service");
2969     if (ser == "region") prefix = "filter0.";
2970     service.lock();
2971     for (int j = 0; j < params.count(); j++) {
2972         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2973     }
2974     service.unlock();
2975
2976     refresh();
2977     return true;
2978 }
2979
2980 bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList params)
2981 {
2982     int index = params.paramValue("kdenlive_ix").toInt();
2983     QString tag =  params.paramValue("tag");
2984
2985     if (!params.paramValue("keyframes").isEmpty() || (tag == "affine" && params.hasParam("background")) || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
2986         // This is a keyframe effect, to edit it, we remove it and re-add it.
2987         bool success = mltRemoveEffect(track, position, index, false);
2988 //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
2989         if (position < GenTime())
2990             success = mltAddTrackEffect(track, params);
2991         else
2992             success = mltAddEffect(track, position, params);
2993 //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
2994         return success;
2995     }
2996     if (position < GenTime()) {
2997         return mltEditTrackEffect(track, params);
2998     }
2999     // find filter
3000     Mlt::Service service(m_mltProducer->parent().get_service());
3001     Mlt::Tractor tractor(service);
3002     Mlt::Producer trackProducer(tractor.track(track));
3003     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3004
3005     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3006     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3007     if (!clip) {
3008         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3009         return false;
3010     }
3011
3012     int duration = clip->get_playtime();
3013     bool doRefresh = true;
3014     // Check if clip is visible in monitor
3015     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3016     if (diff < 0 || diff > duration)
3017         doRefresh = false;
3018     int ct = 0;
3019
3020     Mlt::Filter *filter = clip->filter(ct);
3021     while (filter) {
3022         if (filter->get_int("kdenlive_ix") == index) {
3023             break;
3024         }
3025         ct++;
3026         filter = clip->filter(ct);
3027     }
3028
3029     if (!filter) {
3030         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
3031         // filter was not found, it was probably a disabled filter, so add it to the correct place...
3032
3033         bool success = mltAddEffect(track, position, params);
3034         return success;
3035     }
3036     ct = 0;
3037     QString ser = filter->get("mlt_service");
3038     QList <Mlt::Filter *> filtersList;
3039     service.lock();
3040     if (ser != tag) {
3041         // Effect service changes, delete effect and re-add it
3042         clip->detach(*filter);  
3043         
3044         // Delete all effects after deleted one
3045         filter = clip->filter(ct);
3046         while (filter) {
3047             if (filter->get_int("kdenlive_ix") > index) {
3048                 filtersList.append(filter);
3049                 clip->detach(*filter);
3050             }
3051             else ct++;
3052             filter = clip->filter(ct);
3053         }
3054         
3055         // re-add filter
3056         addFilterToService(*clip, params, clip->get_playtime());
3057         delete clip;
3058         service.unlock();
3059
3060         if (doRefresh) refresh();
3061         return true;
3062     }
3063     if (params.hasParam("_sync_in_out")) {
3064         // This effect must sync in / out with parent clip
3065         params.removeParam("_sync_in_out");
3066         filter->set_in_and_out(clip->get_in(), clip->get_out());
3067     }
3068
3069     for (int j = 0; j < params.count(); j++) {
3070         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
3071     }
3072     
3073     for (int j = 0; j < filtersList.count(); j++) {
3074         clip->attach(*(filtersList.at(j)));
3075     }
3076
3077     delete clip;
3078     service.unlock();
3079
3080     if (doRefresh) refresh();
3081     return true;
3082 }
3083
3084 bool Render::mltEnableEffects(int track, GenTime position, QList <int> effectIndexes, bool disable)
3085 {
3086     if (position < GenTime()) {
3087         return mltEnableTrackEffects(track, effectIndexes, disable);
3088     }
3089     // find filter
3090     Mlt::Service service(m_mltProducer->parent().get_service());
3091     Mlt::Tractor tractor(service);
3092     Mlt::Producer trackProducer(tractor.track(track));
3093     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3094
3095     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3096     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3097     if (!clip) {
3098         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3099         return false;
3100     }
3101
3102     int duration = clip->get_playtime();
3103     bool doRefresh = true;
3104     // Check if clip is visible in monitor
3105     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3106     if (diff < 0 || diff > duration)
3107         doRefresh = false;
3108     int ct = 0;
3109
3110     Mlt::Filter *filter = clip->filter(ct);
3111     while (filter) {
3112         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3113             filter->set("disable", (int) disable);
3114         }
3115         ct++;
3116         filter = clip->filter(ct);
3117     }
3118
3119     delete clip;
3120     service.unlock();
3121
3122     if (doRefresh) refresh();
3123     return true;
3124 }
3125
3126 bool Render::mltEnableTrackEffects(int track, QList <int> effectIndexes, bool disable)
3127 {
3128     Mlt::Service service(m_mltProducer->parent().get_service());
3129     Mlt::Tractor tractor(service);
3130     Mlt::Producer trackProducer(tractor.track(track));
3131     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3132     Mlt::Service clipService(trackPlaylist.get_service());
3133     int ct = 0;
3134
3135     Mlt::Filter *filter = clipService.filter(ct);
3136     while (filter) {
3137         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3138             filter->set("disable", (int) disable);
3139         }
3140         ct++;
3141         filter = clipService.filter(ct);
3142     }
3143     service.unlock();
3144
3145     refresh();
3146     return true;
3147 }
3148
3149 void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
3150 {
3151     Mlt::Service service(m_mltProducer->parent().get_service());
3152     Mlt::Tractor tractor(service);
3153     Mlt::Producer trackProducer(tractor.track(track));
3154     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3155
3156     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3157     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3158     if (!clip) {
3159         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3160         return;
3161     }
3162
3163     Mlt::Service clipService(clip->get_service());
3164     int duration = clip->get_playtime();
3165     bool doRefresh = true;
3166     // Check if clip is visible in monitor
3167     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3168     if (diff < 0 || diff > duration) doRefresh = false;
3169     delete clip;
3170
3171     int ct = 0;
3172     Mlt::Filter *filter = clipService.filter(ct);
3173     while (filter) {
3174         int pos = filter->get_int("kdenlive_ix");
3175         if (pos == oldPos) {
3176             filter->set("kdenlive_ix", newPos);
3177         } else ct++;
3178         filter = clipService.filter(ct);
3179     }
3180     if (doRefresh) refresh();
3181 }
3182
3183 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
3184 {
3185     if (position < GenTime()) {
3186         mltMoveTrackEffect(track, oldPos, newPos);
3187         return;
3188     }
3189     Mlt::Service service(m_mltProducer->parent().get_service());
3190     Mlt::Tractor tractor(service);
3191     Mlt::Producer trackProducer(tractor.track(track));
3192     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3193
3194     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3195     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3196     if (!clip) {
3197         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3198         return;
3199     }
3200
3201     Mlt::Service clipService(clip->get_service());
3202     int duration = clip->get_playtime();
3203     bool doRefresh = true;
3204     // Check if clip is visible in monitor
3205     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3206     if (diff < 0 || diff > duration) doRefresh = false;
3207     delete clip;
3208
3209     int ct = 0;
3210     QList <Mlt::Filter *> filtersList;
3211     Mlt::Filter *filter = clipService.filter(ct);
3212     bool found = false;
3213     if (newPos > oldPos) {
3214         while (filter) {
3215             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3216                 filter->set("kdenlive_ix", newPos);
3217                 filtersList.append(filter);
3218                 clipService.detach(*filter);
3219                 filter = clipService.filter(ct);
3220                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3221                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3222                     ct++;
3223                     filter = clipService.filter(ct);
3224                 }
3225                 found = true;
3226             }
3227             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3228                 filtersList.append(filter);
3229                 clipService.detach(*filter);
3230             } else ct++;
3231             filter = clipService.filter(ct);
3232         }
3233     } else {
3234         while (filter) {
3235             if (filter->get_int("kdenlive_ix") == oldPos) {
3236                 filter->set("kdenlive_ix", newPos);
3237                 filtersList.append(filter);
3238                 clipService.detach(*filter);
3239             } else ct++;
3240             filter = clipService.filter(ct);
3241         }
3242
3243         ct = 0;
3244         filter = clipService.filter(ct);
3245         while (filter) {
3246             int pos = filter->get_int("kdenlive_ix");
3247             if (pos >= newPos) {
3248                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3249                 filtersList.append(filter);
3250                 clipService.detach(*filter);
3251             } else ct++;
3252             filter = clipService.filter(ct);
3253         }
3254     }
3255
3256     for (int i = 0; i < filtersList.count(); i++) {
3257         clipService.attach(*(filtersList.at(i)));
3258     }
3259
3260     if (doRefresh) refresh();
3261 }
3262
3263 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
3264 {
3265     Mlt::Service service(m_mltProducer->parent().get_service());
3266     Mlt::Tractor tractor(service);
3267     Mlt::Producer trackProducer(tractor.track(track));
3268     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3269     Mlt::Service clipService(trackPlaylist.get_service());
3270     int ct = 0;
3271     QList <Mlt::Filter *> filtersList;
3272     Mlt::Filter *filter = clipService.filter(ct);
3273     bool found = false;
3274     if (newPos > oldPos) {
3275         while (filter) {
3276             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3277                 filter->set("kdenlive_ix", newPos);
3278                 filtersList.append(filter);
3279                 clipService.detach(*filter);
3280                 filter = clipService.filter(ct);
3281                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3282                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3283                     ct++;
3284                     filter = clipService.filter(ct);
3285                 }
3286                 found = true;
3287             }
3288             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3289                 filtersList.append(filter);
3290                 clipService.detach(*filter);
3291             } else ct++;
3292             filter = clipService.filter(ct);
3293         }
3294     } else {
3295         while (filter) {
3296             if (filter->get_int("kdenlive_ix") == oldPos) {
3297                 filter->set("kdenlive_ix", newPos);
3298                 filtersList.append(filter);
3299                 clipService.detach(*filter);
3300             } else ct++;
3301             filter = clipService.filter(ct);
3302         }
3303
3304         ct = 0;
3305         filter = clipService.filter(ct);
3306         while (filter) {
3307             int pos = filter->get_int("kdenlive_ix");
3308             if (pos >= newPos) {
3309                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3310                 filtersList.append(filter);
3311                 clipService.detach(*filter);
3312             } else ct++;
3313             filter = clipService.filter(ct);
3314         }
3315     }
3316
3317     for (int i = 0; i < filtersList.count(); i++) {
3318         clipService.attach(*(filtersList.at(i)));
3319     }
3320     refresh();
3321 }
3322
3323 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration, bool refresh)
3324 {
3325     Mlt::Service service(m_mltProducer->parent().get_service());
3326     Mlt::Tractor tractor(service);
3327     Mlt::Producer trackProducer(tractor.track(info.track));
3328     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3329
3330     /* // Display playlist info
3331     kDebug()<<"////////////  BEFORE RESIZE";
3332     for (int i = 0; i < trackPlaylist.count(); i++) {
3333     int blankStart = trackPlaylist.clip_start(i);
3334     int blankDuration = trackPlaylist.clip_length(i) - 1;
3335     QString blk;
3336     if (trackPlaylist.is_blank(i)) blk = "(blank)";
3337     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
3338     }*/
3339
3340     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
3341         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3342         return false;
3343     }
3344     service.lock();
3345     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
3346     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
3347     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3348
3349     int previousStart = clip->get_in();
3350     int newDuration = (int) clipDuration.frames(m_fps) - 1;
3351     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
3352
3353     int currentOut = newDuration + previousStart;
3354     if (currentOut > clip->get_length()) {
3355         clip->parent().set("length", currentOut + 1);
3356         clip->parent().set("out", currentOut);
3357         clip->set("length", currentOut + 1);
3358     }
3359
3360     /*if (newDuration > clip->get_out()) {
3361         clip->parent().set_in_and_out(0, newDuration + 1);
3362         clip->set_in_and_out(0, newDuration + 1);
3363     }*/
3364     delete clip;
3365     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
3366     trackPlaylist.consolidate_blanks(0);
3367     // skip to next clip
3368     clipIndex++;
3369     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
3370     if (diff > 0) {
3371         // clip was made longer, trim next blank if there is one.
3372         if (clipIndex < trackPlaylist.count()) {
3373             // If this is not the last clip in playlist
3374             if (trackPlaylist.is_blank(clipIndex)) {
3375                 int blankStart = trackPlaylist.clip_start(clipIndex);
3376                 int blankDuration = trackPlaylist.clip_length(clipIndex);
3377                 if (diff > blankDuration) {
3378                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
3379                 }
3380                 if (diff - blankDuration == 0) {
3381                     trackPlaylist.remove(clipIndex);
3382                 } else trackPlaylist.remove_region(blankStart, diff);
3383             } else {
3384                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
3385             }
3386         }
3387     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
3388     trackPlaylist.consolidate_blanks(0);
3389     service.unlock();
3390
3391     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
3392     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3393         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
3394         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3395         ItemInfo transpinfo;
3396         transpinfo.startPos = info.startPos;
3397         transpinfo.endPos = info.startPos + clipDuration;
3398         transpinfo.track = info.track;
3399         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3400     }*/
3401     if (refresh) m_mltConsumer->set("refresh", 1);
3402     return true;
3403 }
3404
3405 void Render::mltChangeTrackState(int track, bool mute, bool blind)
3406 {
3407     Mlt::Service service(m_mltProducer->parent().get_service());
3408     Mlt::Tractor tractor(service);
3409     Mlt::Producer trackProducer(tractor.track(track));
3410
3411     // Make sure muting will not produce problems with our audio mixing transition,
3412     // because audio mixing is done between each track and the lowest one
3413     bool audioMixingBroken = false;
3414     if (mute && trackProducer.get_int("hide") < 2 ) {
3415             // We mute a track with sound
3416             if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3417             kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
3418     }
3419     else if (!mute && trackProducer.get_int("hide") > 1 ) {
3420             // We un-mute a previously muted track
3421             if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3422     }
3423
3424     if (mute) {
3425         if (blind) trackProducer.set("hide", 3);
3426         else trackProducer.set("hide", 2);
3427     } else if (blind) {
3428         trackProducer.set("hide", 1);
3429     } else {
3430         trackProducer.set("hide", 0);
3431     }
3432     if (audioMixingBroken) fixAudioMixing(tractor);
3433
3434     tractor.multitrack()->refresh();
3435     tractor.refresh();
3436     refresh();
3437 }
3438
3439 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3440 {
3441     for (int i = 1; i < tractor.count(); i++) {
3442         Mlt::Producer trackProducer(tractor.track(i));
3443         if (trackProducer.get_int("hide") < 2) return i;
3444     }
3445     return tractor.count() - 1;
3446 }
3447
3448 void Render::fixAudioMixing(Mlt::Tractor tractor)
3449 {
3450     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3451     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3452
3453     mlt_service serv = m_mltProducer->parent().get_service();
3454     Mlt::Field *field = tractor.field();
3455     mlt_service_lock(serv);
3456
3457     mlt_service nextservice = mlt_service_get_producer(serv);
3458     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3459     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3460     QString resource = mlt_properties_get(properties, "mlt_service");
3461
3462     mlt_service nextservicetodisconnect;
3463      // Delete all audio mixing transitions
3464     while (mlt_type == "transition") {
3465         if (resource == "mix") {
3466             nextservicetodisconnect = nextservice;
3467             nextservice = mlt_service_producer(nextservice);
3468             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3469         }
3470         else nextservice = mlt_service_producer(nextservice);
3471         if (nextservice == NULL) break;
3472         properties = MLT_SERVICE_PROPERTIES(nextservice);
3473         mlt_type = mlt_properties_get(properties, "mlt_type");
3474         resource = mlt_properties_get(properties, "mlt_service");
3475     }
3476
3477     // Re-add correct audio transitions
3478     for (int i = lowestTrack + 1; i < tractor.count(); i++) {
3479         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3480         transition->set("always_active", 1);
3481         transition->set("combine", 1);
3482         transition->set("internal_added", 237);
3483         field->plant_transition(*transition, lowestTrack, i);
3484     }
3485     mlt_service_unlock(serv);
3486 }
3487
3488 bool Render::mltResizeClipCrop(ItemInfo info, GenTime newCropStart)
3489 {
3490     Mlt::Service service(m_mltProducer->parent().get_service());
3491     int newCropFrame = (int) newCropStart.frames(m_fps);
3492     Mlt::Tractor tractor(service);
3493     Mlt::Producer trackProducer(tractor.track(info.track));
3494     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3495     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3496         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3497         return false;
3498     }
3499     service.lock();
3500     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3501     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3502     if (clip == NULL) {
3503         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3504         service.unlock();
3505         return false;
3506     }
3507     int previousStart = clip->get_in();
3508     int previousOut = clip->get_out();
3509     delete clip;
3510     if (previousStart == newCropFrame) {
3511         kDebug() << "////////  No ReSIZING Required";
3512         service.unlock();
3513         return true;
3514     }
3515     int frameOffset = newCropFrame - previousStart;
3516     trackPlaylist.resize_clip(clipIndex, newCropFrame, previousOut + frameOffset);
3517     service.unlock();
3518     m_mltConsumer->set("refresh", 1);
3519     return true;
3520 }
3521
3522 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3523 {
3524     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3525     Mlt::Service service(m_mltProducer->parent().get_service());
3526     int moveFrame = (int) diff.frames(m_fps);
3527     Mlt::Tractor tractor(service);
3528     Mlt::Producer trackProducer(tractor.track(info.track));
3529     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3530     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3531         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3532         return false;
3533     }
3534     service.lock();
3535     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3536     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3537     if (clip == NULL || clip->is_blank()) {
3538         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3539         service.unlock();
3540         return false;
3541     }
3542     int previousStart = clip->get_in();
3543     int previousOut = clip->get_out();
3544
3545     previousStart += moveFrame;
3546
3547     if (previousStart < 0) {
3548         // this is possible for images and color clips
3549         previousOut -= previousStart;
3550         previousStart = 0;
3551     }
3552
3553     int length = previousOut + 1;
3554     if (length > clip->get_length()) {
3555         clip->parent().set("length", length + 1);
3556         clip->parent().set("out", length);
3557         clip->set("length", length + 1);
3558     }
3559     delete clip;
3560
3561     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3562     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3563     if (moveFrame > 0) {
3564         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3565     } else {
3566         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3567         int blankIndex = clipIndex - 1;
3568         int blankLength = trackPlaylist.clip_length(blankIndex);
3569         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3570         if (! trackPlaylist.is_blank(blankIndex)) {
3571             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3572         }
3573         if (blankLength + moveFrame == 0)
3574             trackPlaylist.remove(blankIndex);
3575         else
3576             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3577     }
3578     trackPlaylist.consolidate_blanks(0);
3579     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3580         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3581         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3582         ItemInfo transpinfo;
3583         transpinfo.startPos = info.startPos + diff;
3584         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3585         transpinfo.track = info.track;
3586         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3587     }*/
3588     //m_mltConsumer->set("refresh", 1);
3589     service.unlock();
3590     m_mltConsumer->set("refresh", 1);
3591     return true;
3592 }
3593
3594 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3595 {
3596     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3597 }
3598
3599
3600 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3601 {
3602     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3603         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3604         return false;
3605     }
3606
3607     Mlt::Producer trackProducer(tractor->track(track));
3608     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3609     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3610     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3611     if (clipProducer == NULL || clipProducer->is_blank()) {
3612         kDebug() << "// ERROR UPDATING CLIP PROD";
3613         delete clipProducer;
3614         return false;
3615     }
3616     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3617     if (!clip || !clip->is_valid()) {
3618         if (clip) delete clip;
3619         delete clipProducer;
3620         return false;
3621     }
3622     // move all effects to the correct producer
3623     mltPasteEffects(clipProducer, clip);
3624     trackPlaylist.insert_at(pos, clip, 1);
3625     delete clip;
3626     delete clipProducer;
3627     return true;
3628 }
3629
3630 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3631 {
3632     Mlt::Service service(m_mltProducer->parent().get_service());
3633     if (service.type() != tractor_type) {
3634         kWarning() << "// TRACTOR PROBLEM";
3635         return false;
3636     }
3637
3638     Mlt::Tractor tractor(service);
3639     service.lock();
3640     Mlt::Producer trackProducer(tractor.track(startTrack));
3641     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3642     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3643     int clipDuration = trackPlaylist.clip_length(clipIndex);
3644     bool checkLength = false;
3645     if (endTrack == startTrack) {
3646         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3647         if (!overwrite) {
3648             bool success = true;
3649             if (!trackPlaylist.is_blank_at(moveEnd) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
3650                 success = false;
3651             }
3652             else {
3653                 // Check that the destination region is empty
3654                 trackPlaylist.consolidate_blanks(0);
3655                 int destinationIndex = trackPlaylist.get_clip_index_at(moveEnd);
3656                 if (destinationIndex < trackPlaylist.count() - 1) {
3657                     // We are not at the end of the track
3658                     int blankSize = trackPlaylist.blanks_from(destinationIndex, 1);
3659                     // Make sure we have enough place to insert clip
3660                     if (blankSize - clipDuration - (moveEnd - trackPlaylist.clip_start(destinationIndex)) < 0) success = false;
3661                 }
3662             }
3663             if (!success) {
3664                 if (clipProducer) {
3665                     trackPlaylist.insert_at(moveStart, clipProducer, 1);
3666                     delete clipProducer;
3667                 }
3668                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3669                 service.unlock();
3670                 return false;
3671             }
3672         }
3673         
3674         if (overwrite) {
3675             trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3676             int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
3677             trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
3678         }
3679         int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3680         if (newIndex == -1) {
3681             kDebug()<<"// CANNOT MOVE CLIP TO: "<<moveEnd;
3682             trackPlaylist.insert_at(moveStart, clipProducer, 1);
3683             delete clipProducer;
3684             service.unlock();
3685             return false;
3686         }
3687         trackPlaylist.consolidate_blanks(1);
3688         delete clipProducer;
3689         if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
3690     } else {
3691         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3692         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3693         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3694             // error, destination is not empty
3695             kDebug() << "Cannot move: Destination is not empty";
3696             service.unlock();
3697             return false;
3698         } else {
3699             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3700             if (!clipProducer || clipProducer->is_blank()) {
3701                 // error, destination is not empty
3702                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3703                 if (clipProducer) delete clipProducer;
3704                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3705                 service.unlock();
3706                 return false;
3707             }
3708             trackPlaylist.consolidate_blanks(0);
3709             destTrackPlaylist.consolidate_blanks(1);
3710             Mlt::Producer *clip;
3711             // check if we are moving a slowmotion producer
3712             QString serv = clipProducer->parent().get("mlt_service");
3713             QString currentid = clipProducer->parent().get("id");
3714             if (serv == "framebuffer") {
3715                 clip = clipProducer;
3716             } else {
3717                 if (prod == NULL) {
3718                     // Special case: prod is null when using placeholder clips.
3719                     // in that case, use the producer existing in playlist. Note that
3720                     // it will bypass the one producer per track logic and might cause
3721                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3722                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3723                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3724             }
3725
3726             // move all effects to the correct producer
3727             mltPasteEffects(clipProducer, clip);
3728
3729             if (overwrite) {
3730                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3731                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3732                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3733             }
3734
3735             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3736
3737             if (clip == clipProducer) {
3738                 delete clip;
3739                 clip = NULL;
3740             } else {
3741                 delete clip;
3742                 delete clipProducer;
3743             }
3744             destTrackPlaylist.consolidate_blanks(0);
3745             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3746                 kDebug() << "//////// moving clip transparency";
3747                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3748             }*/
3749             if (clipIndex > trackPlaylist.count()) checkLength = true;
3750             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3751         }
3752     }
3753     service.unlock();
3754     if (checkLength) mltCheckLength(&tractor);
3755     //askForRefresh();
3756     //m_mltConsumer->set("refresh", 1);
3757     return true;
3758 }
3759
3760
3761 QList <int> Render::checkTrackSequence(int track)
3762 {
3763     QList <int> list;
3764     Mlt::Service service(m_mltProducer->parent().get_service());
3765     if (service.type() != tractor_type) {
3766         kWarning() << "// TRACTOR PROBLEM";
3767         return list;
3768     }
3769     Mlt::Tractor tractor(service);
3770     service.lock();
3771     Mlt::Producer trackProducer(tractor.track(track));
3772     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3773     int clipNb = trackPlaylist.count();
3774     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3775     for (int i = 0; i < clipNb; i++) {
3776         Mlt::Producer *c = trackPlaylist.get_clip(i);
3777         int pos = trackPlaylist.clip_start(i);
3778         if (!list.contains(pos)) list.append(pos);
3779         pos += c->get_playtime();
3780         if (!list.contains(pos)) list.append(pos);
3781         delete c;
3782     }
3783     return list;
3784 }
3785
3786 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3787 {
3788     int new_in = (int)newIn.frames(m_fps);
3789     int new_out = (int)newOut.frames(m_fps) - 1;
3790     if (new_in >= new_out) return false;
3791     int old_in = (int)oldIn.frames(m_fps);
3792     int old_out = (int)oldOut.frames(m_fps) - 1;
3793
3794     Mlt::Service service(m_mltProducer->parent().get_service());
3795     Mlt::Tractor tractor(service);
3796     Mlt::Field *field = tractor.field();
3797
3798     bool doRefresh = true;
3799     // Check if clip is visible in monitor
3800     int diff = old_out - m_mltProducer->position();
3801     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3802     if (doRefresh) {
3803         diff = new_out - m_mltProducer->position();
3804         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3805     }
3806     service.lock();
3807
3808     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3809     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3810     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3811     QString resource = mlt_properties_get(properties, "mlt_service");
3812     int old_pos = (int)(old_in + old_out) / 2;
3813     bool found = false;
3814
3815     while (mlt_type == "transition") {
3816         Mlt::Transition transition((mlt_transition) nextservice);
3817         nextservice = mlt_service_producer(nextservice);
3818         int currentTrack = transition.get_b_track();
3819         int currentIn = (int) transition.get_in();
3820         int currentOut = (int) transition.get_out();
3821
3822         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3823             found = true;
3824             if (newTrack - startTrack != 0) {
3825                 Mlt::Properties trans_props(transition.get_properties());
3826                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3827                 Mlt::Properties new_trans_props(new_transition.get_properties());
3828                 new_trans_props.inherit(trans_props);
3829                 new_transition.set_in_and_out(new_in, new_out);
3830                 field->disconnect_service(transition);
3831                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3832                 //field->plant_transition(new_transition, newTransitionTrack, newTrack);
3833             } else transition.set_in_and_out(new_in, new_out);
3834             break;
3835         }
3836         if (nextservice == NULL) break;
3837         properties = MLT_SERVICE_PROPERTIES(nextservice);
3838         mlt_type = mlt_properties_get(properties, "mlt_type");
3839         resource = mlt_properties_get(properties, "mlt_service");
3840     }
3841     service.unlock();
3842     if (doRefresh) refresh();
3843     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3844     return found;
3845 }
3846
3847
3848 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3849 {
3850     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3851     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3852     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3853     QString resource = mlt_properties_get(properties, "mlt_service");
3854     QList <Mlt::Transition *> trList;
3855     mlt_properties insertproperties = tr.get_properties();
3856     QString insertresource = mlt_properties_get(insertproperties, "mlt_service");
3857     bool isMixTransition = insertresource == "mix";
3858
3859     while (mlt_type == "transition") {
3860         Mlt::Transition transition((mlt_transition) nextservice);
3861         nextservice = mlt_service_producer(nextservice);
3862         int aTrack = transition.get_a_track();
3863         int bTrack = transition.get_b_track();
3864         if ((isMixTransition || resource != "mix") && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3865             Mlt::Properties trans_props(transition.get_properties());
3866             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3867             Mlt::Properties new_trans_props(cp->get_properties());
3868             new_trans_props.inherit(trans_props);
3869             trList.append(cp);
3870             field->disconnect_service(transition);
3871         }
3872         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3873
3874         if (nextservice == NULL) break;
3875         properties = MLT_SERVICE_PROPERTIES(nextservice);
3876         mlt_type = mlt_properties_get(properties, "mlt_type");
3877         resource = mlt_properties_get(properties, "mlt_service");
3878     }
3879     field->plant_transition(tr, a_track, b_track);
3880
3881     // re-add upper transitions
3882     for (int i = trList.count() - 1; i >= 0; i--) {
3883         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3884         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3885     }
3886     qDeleteAll(trList);
3887 }
3888
3889 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3890 {
3891     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3892     else {
3893         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3894         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3895         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3896     }
3897
3898     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3899 }
3900
3901 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3902 {
3903     mlt_service serv = m_mltProducer->parent().get_service();
3904     mlt_service_lock(serv);
3905
3906     mlt_service nextservice = mlt_service_get_producer(serv);
3907     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3908     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3909     QString resource = mlt_properties_get(properties, "mlt_service");
3910     int in_pos = (int) in.frames(m_fps);
3911     int out_pos = (int) out.frames(m_fps) - 1;
3912
3913     while (mlt_type == "transition") {
3914         mlt_transition tr = (mlt_transition) nextservice;
3915         int currentTrack = mlt_transition_get_b_track(tr);
3916         int currentBTrack = mlt_transition_get_a_track(tr);
3917         int currentIn = (int) mlt_transition_get_in(tr);
3918         int currentOut = (int) mlt_transition_get_out(tr);
3919
3920         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
3921         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
3922             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
3923             QMap<QString, QString>::Iterator it;
3924             QString key;
3925             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
3926
3927             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
3928             if (currentId != xml.attribute("id")) {
3929                 // The transition ID is not the same, so reset all properties
3930                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
3931                 // Cleanup previous properties
3932                 QStringList permanentProps;
3933                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
3934                 permanentProps << "out" << "a_track" << "b_track";
3935                 for (int i = 0; i < mlt_properties_count(transproperties); i++) {
3936                     QString propName = mlt_properties_get_name(transproperties, i);
3937                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
3938                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
3939                     }
3940                 }
3941             }
3942
3943             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
3944             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
3945
3946             if (currentBTrack != a_track) {
3947                 mlt_properties_set_int(transproperties, "a_track", a_track);
3948             }
3949             for (it = map.begin(); it != map.end(); ++it) {
3950                 key = it.key();
3951                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
3952                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
3953                 //filter->set("kdenlive_id", id);
3954             }
3955             break;
3956         }
3957         nextservice = mlt_service_producer(nextservice);
3958         if (nextservice == NULL) break;
3959         properties = MLT_SERVICE_PROPERTIES(nextservice);
3960         mlt_type = mlt_properties_get(properties, "mlt_type");
3961         resource = mlt_properties_get(properties, "mlt_service");
3962     }
3963     mlt_service_unlock(serv);
3964     //askForRefresh();
3965     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3966 }
3967
3968 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
3969 {
3970     mlt_service serv = m_mltProducer->parent().get_service();
3971     mlt_service_lock(serv);
3972
3973     Mlt::Service service(serv);
3974     Mlt::Tractor tractor(service);
3975     Mlt::Field *field = tractor.field();
3976
3977     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3978
3979     mlt_service nextservice = mlt_service_get_producer(serv);
3980     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3981     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3982     QString resource = mlt_properties_get(properties, "mlt_service");
3983
3984     const int old_pos = (int)((in + out).frames(m_fps) / 2);
3985     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
3986
3987     while (mlt_type == "transition") {
3988         mlt_transition tr = (mlt_transition) nextservice;
3989         int currentTrack = mlt_transition_get_b_track(tr);
3990         int currentIn = (int) mlt_transition_get_in(tr);
3991         int currentOut = (int) mlt_transition_get_out(tr);
3992         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3993
3994         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3995             mlt_field_disconnect_service(field->get_field(), nextservice);
3996             break;
3997         }
3998         nextservice = mlt_service_producer(nextservice);
3999         if (nextservice == NULL) break;
4000         properties = MLT_SERVICE_PROPERTIES(nextservice);
4001         mlt_type = mlt_properties_get(properties, "mlt_type");
4002         resource = mlt_properties_get(properties, "mlt_service");
4003     }
4004     mlt_service_unlock(serv);
4005     //askForRefresh();
4006     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
4007 }
4008
4009 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
4010 {
4011     QDomNodeList attribs = xml.elementsByTagName("parameter");
4012     QMap<QString, QString> map;
4013     for (int i = 0; i < attribs.count(); i++) {
4014         QDomElement e = attribs.item(i).toElement();
4015         QString name = e.attribute("name");
4016         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
4017         map[name] = e.attribute("default");
4018         if (!e.attribute("value").isEmpty()) {
4019             map[name] = e.attribute("value");
4020         }
4021         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
4022             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
4023             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
4024         }
4025
4026         if (e.attribute("namedesc").contains(';')) {
4027             QString format = e.attribute("format");
4028             QStringList separators = format.split("%d", QString::SkipEmptyParts);
4029             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
4030             QString neu;
4031             QTextStream txtNeu(&neu);
4032             if (values.size() > 0)
4033                 txtNeu << (int)values[0].toDouble();
4034             int i = 0;
4035             for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
4036                 txtNeu << separators[i];
4037                 txtNeu << (int)(values[i+1].toDouble());
4038             }
4039             if (i < separators.size())
4040                 txtNeu << separators[i];
4041             map[e.attribute("name")] = neu;
4042         }
4043
4044     }
4045     return map;
4046 }
4047
4048 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
4049 {
4050     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
4051     Mlt::Service service(m_mltProducer->parent().get_service());
4052     Mlt::Tractor tractor(service);
4053     Mlt::Field *field = tractor.field();
4054
4055     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
4056     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
4057     transition->set("transparency", id);
4058     transition->set("fill", 1);
4059     transition->set("internal_added", 237);
4060     field->plant_transition(*transition, transitiontrack, info.track);
4061     refresh();
4062 }
4063
4064 void Render::mltDeleteTransparency(int pos, int track, int id)
4065 {
4066     Mlt::Service service(m_mltProducer->parent().get_service());
4067     Mlt::Tractor tractor(service);
4068     Mlt::Field *field = tractor.field();
4069
4070     //if (do_refresh) m_mltConsumer->set("refresh", 0);
4071     mlt_service serv = m_mltProducer->parent().get_service();
4072
4073     mlt_service nextservice = mlt_service_get_producer(serv);
4074     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4075     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4076     QString resource = mlt_properties_get(properties, "mlt_service");
4077
4078     while (mlt_type == "transition") {
4079         mlt_transition tr = (mlt_transition) nextservice;
4080         int currentTrack = mlt_transition_get_b_track(tr);
4081         int currentIn = (int) mlt_transition_get_in(tr);
4082         int currentOut = (int) mlt_transition_get_out(tr);
4083         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4084         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
4085
4086         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
4087             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
4088             mlt_field_disconnect_service(field->get_field(), nextservice);
4089             break;
4090         }
4091         nextservice = mlt_service_producer(nextservice);
4092         if (nextservice == NULL) break;
4093         properties = MLT_SERVICE_PROPERTIES(nextservice);
4094         mlt_type = mlt_properties_get(properties, "mlt_type");
4095         resource = mlt_properties_get(properties, "mlt_service");
4096     }
4097     //if (do_refresh) m_mltConsumer->set("refresh", 1);
4098 }
4099
4100 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
4101 {
4102     Mlt::Service service(m_mltProducer->parent().get_service());
4103     Mlt::Tractor tractor(service);
4104
4105     service.lock();
4106     m_mltConsumer->set("refresh", 0);
4107
4108     mlt_service serv = m_mltProducer->parent().get_service();
4109     mlt_service nextservice = mlt_service_get_producer(serv);
4110     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4111     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4112     QString resource = mlt_properties_get(properties, "mlt_service");
4113     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
4114     while (mlt_type == "transition") {
4115         mlt_transition tr = (mlt_transition) nextservice;
4116         int currentTrack = mlt_transition_get_b_track(tr);
4117         int currentIn = (int) mlt_transition_get_in(tr);
4118         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
4119         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4120         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
4121         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
4122             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
4123             mlt_transition_set_in_and_out(tr, newStart, newEnd);
4124             break;
4125         }
4126         nextservice = mlt_service_producer(nextservice);
4127         if (nextservice == NULL) break;
4128         properties = MLT_SERVICE_PROPERTIES(nextservice);
4129         mlt_type = mlt_properties_get(properties, "mlt_type");
4130         resource = mlt_properties_get(properties, "mlt_service");
4131     }
4132     service.unlock();
4133     m_mltConsumer->set("refresh", 1);
4134
4135 }
4136
4137 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
4138 {
4139     Mlt::Service service(m_mltProducer->parent().get_service());
4140     Mlt::Tractor tractor(service);
4141
4142     service.lock();
4143     m_mltConsumer->set("refresh", 0);
4144
4145     mlt_service serv = m_mltProducer->parent().get_service();
4146     mlt_service nextservice = mlt_service_get_producer(serv);
4147     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4148     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4149     QString resource = mlt_properties_get(properties, "mlt_service");
4150
4151     while (mlt_type == "transition") {
4152         mlt_transition tr = (mlt_transition) nextservice;
4153         int currentTrack = mlt_transition_get_b_track(tr);
4154         int currentaTrack = mlt_transition_get_a_track(tr);
4155         int currentIn = (int) mlt_transition_get_in(tr);
4156         int currentOut = (int) mlt_transition_get_out(tr);
4157         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4158         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4159         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
4160         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
4161             kDebug() << "//////MOVING";
4162             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
4163             if (endTrack != startTrack) {
4164                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4165                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
4166                 mlt_properties_set_int(properties, "b_track", endTrack);
4167             }
4168             break;
4169         }
4170         nextservice = mlt_service_producer(nextservice);
4171         if (nextservice == NULL) break;
4172         properties = MLT_SERVICE_PROPERTIES(nextservice);
4173         mlt_type = mlt_properties_get(properties, "mlt_type");
4174         resource = mlt_properties_get(properties, "mlt_service");
4175     }
4176     service.unlock();
4177     m_mltConsumer->set("refresh", 1);
4178 }
4179
4180
4181 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
4182 {
4183     if (in >= out) return false;
4184     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
4185     Mlt::Service service(m_mltProducer->parent().get_service());
4186
4187     Mlt::Tractor tractor(service);
4188     Mlt::Field *field = tractor.field();
4189
4190     Mlt::Transition transition(*m_mltProfile, tag.toUtf8().constData());
4191     if (out != GenTime())
4192         transition.set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
4193
4194     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
4195     QMap<QString, QString>::Iterator it;
4196     QString key;
4197     if (xml.attribute("automatic") == "1") transition.set("automatic", 1);
4198     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
4199     if (xml.hasAttribute("id"))
4200         transition.set("kdenlive_id", xml.attribute("id").toUtf8().constData());
4201     if (xml.hasAttribute("force_track"))
4202         transition.set("force_track", xml.attribute("force_track").toInt());
4203
4204     for (it = args.begin(); it != args.end(); ++it) {
4205         key = it.key();
4206         if (!it.value().isEmpty())
4207             transition.set(key.toUtf8().constData(), it.value().toUtf8().constData());
4208         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
4209     }
4210     // attach transition
4211     service.lock();
4212     mltPlantTransition(field, transition, a_track, b_track);
4213     // field->plant_transition(*transition, a_track, b_track);
4214     service.unlock();
4215     if (do_refresh) refresh();
4216     return true;
4217 }
4218
4219 void Render::mltSavePlaylist()
4220 {
4221     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
4222     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
4223     fileConsumer.set("resource", "/tmp/playlist.mlt");
4224
4225     Mlt::Service service(m_mltProducer->get_service());
4226
4227     fileConsumer.connect(service);
4228     fileConsumer.start();
4229 }
4230
4231 const QList <Mlt::Producer *> Render::producersList()
4232 {
4233     QList <Mlt::Producer *> prods;
4234     if (m_mltProducer == NULL) return prods;
4235     Mlt::Service service(m_mltProducer->parent().get_service());
4236     if (service.type() != tractor_type) return prods;
4237     Mlt::Tractor tractor(service);
4238     QStringList ids;
4239
4240     int trackNb = tractor.count();
4241     for (int t = 1; t < trackNb; t++) {
4242         Mlt::Producer *tt = tractor.track(t);
4243         Mlt::Producer trackProducer(tt);
4244         delete tt;
4245         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4246         if (!trackPlaylist.is_valid()) continue;
4247         int clipNb = trackPlaylist.count();
4248         for (int i = 0; i < clipNb; i++) {
4249             Mlt::Producer *c = trackPlaylist.get_clip(i);
4250             if (c == NULL) continue;
4251             QString prodId = c->parent().get("id");
4252             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
4253                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4254                 if (nprod) {
4255                     ids.append(prodId);
4256                     prods.append(nprod);
4257                 }
4258             }
4259             delete c;
4260         }
4261     }
4262     return prods;
4263 }
4264
4265 void Render::fillSlowMotionProducers()
4266 {
4267     if (m_mltProducer == NULL) return;
4268     Mlt::Service service(m_mltProducer->parent().get_service());
4269     if (service.type() != tractor_type) return;
4270
4271     Mlt::Tractor tractor(service);
4272
4273     int trackNb = tractor.count();
4274     for (int t = 1; t < trackNb; t++) {
4275         Mlt::Producer *tt = tractor.track(t);
4276         Mlt::Producer trackProducer(tt);
4277         delete tt;
4278         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4279         if (!trackPlaylist.is_valid()) continue;
4280         int clipNb = trackPlaylist.count();
4281         for (int i = 0; i < clipNb; i++) {
4282             Mlt::Producer *c = trackPlaylist.get_clip(i);
4283             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4284             if (nprod) {
4285                 QString id = nprod->parent().get("id");
4286                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
4287                     // this is a slowmotion producer, add it to the list
4288                     QString url = QString::fromUtf8(nprod->get("resource"));
4289                     int strobe = nprod->get_int("strobe");
4290                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
4291                     if (!m_slowmotionProducers.contains(url)) {
4292                         m_slowmotionProducers.insert(url, nprod);
4293                     }
4294                 } else delete nprod;
4295             }
4296             delete c;
4297         }
4298     }
4299 }
4300
4301 QList <TransitionInfo> Render::mltInsertTrack(int ix, bool videoTrack)
4302 {
4303     Mlt::Service service(m_mltProducer->parent().get_service());
4304     if (service.type() != tractor_type) {
4305         kWarning() << "// TRACTOR PROBLEM";
4306         return QList <TransitionInfo> ();
4307     }
4308     blockSignals(true);
4309     service.lock();
4310     Mlt::Tractor tractor(service);
4311     QList <TransitionInfo> transitionInfos;
4312     Mlt::Playlist playlist;
4313     int ct = tractor.count();
4314     if (ix > ct) {
4315         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
4316         ix = ct;
4317     }
4318
4319     int pos = ix;
4320     if (pos < ct) {
4321         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
4322         tractor.set_track(playlist, pos);
4323         Mlt::Producer newProd(tractor.track(pos));
4324         if (!videoTrack) newProd.set("hide", 1);
4325         pos++;
4326         for (; pos <= ct; pos++) {
4327             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
4328             tractor.set_track(*prodToMove, pos);
4329             prodToMove = prodToMove2;
4330         }
4331     } else {
4332         tractor.set_track(playlist, ix);
4333         Mlt::Producer newProd(tractor.track(ix));
4334         if (!videoTrack) newProd.set("hide", 1);
4335     }
4336     checkMaxThreads();
4337
4338     // Move transitions
4339     mlt_service serv = m_mltProducer->parent().get_service();
4340     mlt_service nextservice = mlt_service_get_producer(serv);
4341     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4342     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4343     QString resource = mlt_properties_get(properties, "mlt_service");
4344     Mlt::Field *field = tractor.field();
4345     QList <Mlt::Transition *> trList;
4346
4347     while (mlt_type == "transition") {
4348         if (resource != "mix") {
4349             Mlt::Transition transition((mlt_transition) nextservice);
4350             nextservice = mlt_service_producer(nextservice);
4351             int currentbTrack = transition.get_b_track();
4352             int currentaTrack = transition.get_a_track();
4353             bool trackChanged = false;
4354             bool forceTransitionTrack = false;
4355             if (currentbTrack >= ix) {
4356                 if (currentbTrack == ix && currentaTrack < ix) forceTransitionTrack = true;
4357                 currentbTrack++;
4358                 trackChanged = true;
4359             }
4360             if (currentaTrack >= ix) {
4361                 currentaTrack++;
4362                 trackChanged = true;
4363             }
4364             kDebug()<<"// Newtrans: "<<currentaTrack<<"/"<<currentbTrack;
4365             
4366             // disconnect all transitions
4367             Mlt::Properties trans_props(transition.get_properties());
4368             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
4369             Mlt::Properties new_trans_props(cp->get_properties());
4370             new_trans_props.inherit(trans_props);
4371             
4372             if (trackChanged) {
4373                 // Transition track needs to be adjusted
4374                 cp->set("a_track", currentaTrack);
4375                 cp->set("b_track", currentbTrack);
4376                 // Check if transition track was changed and needs to be forced
4377                 if (forceTransitionTrack) cp->set("force_track", 1);
4378                 TransitionInfo trInfo;
4379                 trInfo.startPos = GenTime(transition.get_in(), m_fps);
4380                 trInfo.a_track = currentaTrack;
4381                 trInfo.b_track = currentbTrack;
4382                 trInfo.forceTrack = cp->get_int("force_track");
4383                 transitionInfos.append(trInfo);
4384             }
4385             trList.append(cp);
4386             field->disconnect_service(transition);
4387         }
4388         else nextservice = mlt_service_producer(nextservice);
4389         if (nextservice == NULL) break;
4390         properties = MLT_SERVICE_PROPERTIES(nextservice);
4391         mlt_type = mlt_properties_get(properties, "mlt_type");
4392         resource = mlt_properties_get(properties, "mlt_service");
4393     }
4394
4395     // Add audio mix transition to last track
4396     Mlt::Transition transition(*m_mltProfile, "mix");
4397     transition.set("a_track", 1);
4398     transition.set("b_track", ct);
4399     transition.set("always_active", 1);
4400     transition.set("internal_added", 237);
4401     transition.set("combine", 1);
4402     mltPlantTransition(field, transition, 1, ct);
4403     
4404     // re-add transitions
4405     for (int i = trList.count() - 1; i >= 0; i--) {
4406         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
4407     }
4408     qDeleteAll(trList);
4409     
4410     service.unlock();
4411     blockSignals(false);
4412     return transitionInfos;
4413 }
4414
4415
4416 void Render::mltDeleteTrack(int ix)
4417 {
4418     QDomDocument doc;
4419     doc.setContent(sceneList(), false);
4420     int tracksCount = doc.elementsByTagName("track").count() - 1;
4421     QDomNode track = doc.elementsByTagName("track").at(ix);
4422     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
4423     QDomNodeList transitions = doc.elementsByTagName("transition");
4424     for (int i = 0; i < transitions.count(); i++) {
4425         QDomElement e = transitions.at(i).toElement();
4426         QDomNodeList props = e.elementsByTagName("property");
4427         QMap <QString, QString> mappedProps;
4428         for (int j = 0; j < props.count(); j++) {
4429             QDomElement f = props.at(j).toElement();
4430             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
4431         }
4432         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
4433             tractor.removeChild(transitions.at(i));
4434             i--;
4435         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
4436             // Transition needs to be moved
4437             int a_track = mappedProps.value("a_track").toInt();
4438             int b_track = mappedProps.value("b_track").toInt();
4439             if (a_track > 0 && a_track >= ix) a_track --;
4440             if (b_track == ix) {
4441                 // transition was on the deleted track, so remove it
4442                 tractor.removeChild(transitions.at(i));
4443                 i--;
4444                 continue;
4445             }
4446             if (b_track > 0 && b_track > ix) b_track --;
4447             for (int j = 0; j < props.count(); j++) {
4448                 QDomElement f = props.at(j).toElement();
4449                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
4450                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
4451             }
4452
4453         }
4454     }
4455     tractor.removeChild(track);
4456     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
4457     setSceneList(doc.toString(), m_mltConsumer->position());
4458     emit refreshDocumentProducers(false, false);
4459 }
4460
4461
4462 void Render::updatePreviewSettings()
4463 {
4464     kDebug() << "////// RESTARTING CONSUMER";
4465     if (!m_mltConsumer || !m_mltProducer) return;
4466     if (m_mltProducer->get_playtime() == 0) return;
4467     QMutexLocker locker(&m_mutex);
4468     Mlt::Service service(m_mltProducer->parent().get_service());
4469     if (service.type() != tractor_type) return;
4470
4471     //m_mltConsumer->set("refresh", 0);
4472     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
4473     m_mltConsumer->purge();
4474     QString scene = sceneList();
4475     int pos = 0;
4476     if (m_mltProducer) {
4477         pos = m_mltProducer->position();
4478     }
4479
4480     setSceneList(scene, pos);
4481 }
4482
4483
4484 QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
4485 {
4486     // Update all frame positions to the new fps value
4487     //WARNING: there are probably some effects or other that hold a frame value
4488     // as parameter and will also need to be updated here!
4489     QDomDocument doc;
4490     doc.setContent(scene);
4491
4492     double factor = new_fps / current_fps;
4493     QDomNodeList producers = doc.elementsByTagName("producer");
4494     for (int i = 0; i < producers.count(); i++) {
4495         QDomElement prod = producers.at(i).toElement();
4496         prod.removeAttribute("in");
4497         prod.removeAttribute("out");
4498
4499         QDomNodeList props = prod.childNodes();
4500         for (int j = 0; j < props.count(); j++) {
4501             QDomElement param =  props.at(j).toElement();
4502             QString paramName = param.attribute("name");
4503             if (paramName.startsWith("meta.") || paramName == "length") {
4504                 prod.removeChild(props.at(j));
4505                 j--;
4506             }
4507         }
4508     }
4509
4510     QDomNodeList entries = doc.elementsByTagName("entry");
4511     for (int i = 0; i < entries.count(); i++) {
4512         QDomElement entry = entries.at(i).toElement();
4513         int in = entry.attribute("in").toInt();
4514         int out = entry.attribute("out").toInt();
4515         in = factor * in + 0.5;
4516         out = factor * out + 0.5;
4517         entry.setAttribute("in", in);
4518         entry.setAttribute("out", out);
4519     }
4520
4521     QDomNodeList blanks = doc.elementsByTagName("blank");
4522     for (int i = 0; i < blanks.count(); i++) {
4523         QDomElement blank = blanks.at(i).toElement();
4524         int length = blank.attribute("length").toInt();
4525         length = factor * length + 0.5;
4526         blank.setAttribute("length", QString::number(length));
4527     }
4528
4529     QDomNodeList filters = doc.elementsByTagName("filter");
4530     for (int i = 0; i < filters.count(); i++) {
4531         QDomElement filter = filters.at(i).toElement();
4532         int in = filter.attribute("in").toInt();
4533         int out = filter.attribute("out").toInt();
4534         in = factor * in + 0.5;
4535         out = factor * out + 0.5;
4536         filter.setAttribute("in", in);
4537         filter.setAttribute("out", out);
4538     }
4539
4540     QDomNodeList transitions = doc.elementsByTagName("transition");
4541     for (int i = 0; i < transitions.count(); i++) {
4542         QDomElement transition = transitions.at(i).toElement();
4543         int in = transition.attribute("in").toInt();
4544         int out = transition.attribute("out").toInt();
4545         in = factor * in + 0.5;
4546         out = factor * out + 0.5;
4547         transition.setAttribute("in", in);
4548         transition.setAttribute("out", out);
4549         QDomNodeList props = transition.childNodes();
4550         for (int j = 0; j < props.count(); j++) {
4551             QDomElement param =  props.at(j).toElement();
4552             QString paramName = param.attribute("name");
4553             if (paramName == "geometry") {
4554                 QString geom = param.firstChild().nodeValue();
4555                 QStringList keys = geom.split(';');
4556                 QStringList newKeys;
4557                 for (int k = 0; k < keys.size(); ++k) {
4558                     if (keys.at(k).contains('=')) {
4559                         int pos = keys.at(k).section('=', 0, 0).toInt();
4560                         pos = factor * pos + 0.5;
4561                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4562                     } else newKeys.append(keys.at(k));
4563                 }
4564                 param.firstChild().setNodeValue(newKeys.join(";"));
4565             }
4566         }
4567     }
4568     QDomElement root = doc.documentElement();
4569     if (!root.isNull()) {
4570         QDomElement tractor = root.firstChildElement("tractor");
4571         int out = tractor.attribute("out").toInt();
4572         out = factor * out + 0.5;
4573         tractor.setAttribute("out", out);
4574         emit durationChanged(out);
4575     }
4576
4577     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4578     return doc.toString();
4579 }
4580
4581
4582 void Render::sendFrameUpdate()
4583 {
4584     if (m_mltProducer) {
4585         Mlt::Frame * frame = m_mltProducer->get_frame();
4586         emitFrameUpdated(*frame);
4587         delete frame;
4588     }
4589 }
4590
4591 Mlt::Producer* Render::getProducer()
4592 {
4593     return m_mltProducer;
4594 }
4595
4596 const QString Render::activeClipId()
4597 {
4598     if (m_mltProducer) return m_mltProducer->get("id");
4599     return QString();
4600 }
4601
4602 //static 
4603 bool Render::getBlackMagicDeviceList(KComboBox *devicelist, bool force)
4604 {
4605     if (!force && !KdenliveSettings::decklink_device_found()) return false;
4606     Mlt::Profile profile;
4607     Mlt::Producer bm(profile, "decklink");
4608     int found_devices = 0;
4609     if (bm.is_valid()) {
4610         bm.set("list_devices", 1);
4611         found_devices = bm.get_int("devices");
4612     }
4613     else KdenliveSettings::setDecklink_device_found(false);
4614     if (found_devices <= 0) {
4615         devicelist->setEnabled(false);
4616         return false;
4617     }
4618     KdenliveSettings::setDecklink_device_found(true);
4619     for (int i = 0; i < found_devices; i++) {
4620         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4621         devicelist->addItem(bm.get(tmp));
4622         delete[] tmp;
4623     }
4624     return true;
4625 }
4626
4627 bool Render::getBlackMagicOutputDeviceList(KComboBox *devicelist, bool force)
4628 {
4629     if (!force && !KdenliveSettings::decklink_device_found()) return false;
4630     Mlt::Profile profile;
4631     Mlt::Consumer bm(profile, "decklink");
4632     int found_devices = 0;
4633     if (bm.is_valid()) {
4634         bm.set("list_devices", 1);;
4635         found_devices = bm.get_int("devices");
4636     }
4637     else KdenliveSettings::setDecklink_device_found(false);
4638     if (found_devices <= 0) {
4639         devicelist->setEnabled(false);
4640         return false;
4641     }
4642     KdenliveSettings::setDecklink_device_found(true);
4643     for (int i = 0; i < found_devices; i++) {
4644         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4645         devicelist->addItem(bm.get(tmp));
4646         delete[] tmp;
4647     }
4648     return true;
4649 }
4650
4651 void Render::slotMultiStreamProducerFound(const QString path, QList<int> audio_list, QList<int> video_list, stringMap data)
4652
4653     if (KdenliveSettings::automultistreams()) {
4654         for (int i = 1; i < video_list.count(); i++) {
4655             int vindex = video_list.at(i);
4656             int aindex = 0;
4657             if (i <= audio_list.count() -1) {
4658                 aindex = audio_list.at(i);
4659             }
4660             data.insert("video_index", QString::number(vindex));
4661             data.insert("audio_index", QString::number(aindex));
4662             data.insert("bypassDuplicate", "1");
4663             emit addClip(KUrl(path), data);
4664         }
4665         return;
4666     }
4667     
4668     int width = 60.0 * m_mltProfile->dar();
4669     int swidth = 60.0 * m_mltProfile->width() / m_mltProfile->height();
4670     if (width % 2 == 1) width++;
4671
4672     KDialog dialog(qApp->activeWindow());
4673     dialog.setCaption("Multi Stream Clip");
4674     dialog.setButtons(KDialog::Ok | KDialog::Cancel);
4675     dialog.setButtonText(KDialog::Ok, i18n("Import selected clips"));
4676     QWidget *content = new QWidget(&dialog);
4677     dialog.setMainWidget(content);
4678     QVBoxLayout *vbox = new QVBoxLayout(content);
4679     QLabel *lab1 = new QLabel(i18n("Additional streams for clip\n %1", path), content);
4680     vbox->addWidget(lab1);
4681     QList <QGroupBox*> groupList;
4682     QList <QComboBox*> comboList;
4683     // We start loading the list at 1, video index 0 should already be loaded
4684     for (int j = 1; j < video_list.count(); j++) {
4685         Mlt::Producer multiprod(* m_mltProfile, path.toUtf8().constData());
4686         multiprod.set("video_index", video_list.at(j));
4687         QImage thumb = KThumb::getFrame(&multiprod, 0, swidth, width, 60);
4688         QGroupBox *streamFrame = new QGroupBox(i18n("Video stream %1", video_list.at(j)), content);
4689         streamFrame->setProperty("vindex", video_list.at(j));
4690         groupList << streamFrame;
4691         streamFrame->setCheckable(true);
4692         streamFrame->setChecked(true);
4693         QVBoxLayout *vh = new QVBoxLayout( streamFrame );
4694         QLabel *iconLabel = new QLabel(content);
4695         iconLabel->setPixmap(QPixmap::fromImage(thumb));
4696         vh->addWidget(iconLabel);
4697         if (audio_list.count() > 1) {
4698             QComboBox *cb = new QComboBox(content);
4699             for (int k = 0; k < audio_list.count(); k++) {
4700                 cb->addItem(i18n("Audio stream %1", audio_list.at(k)), audio_list.at(k));
4701             }
4702             comboList << cb;
4703             cb->setCurrentIndex(qMin(j, audio_list.count() - 1));
4704             vh->addWidget(cb);
4705         }
4706         vbox->addWidget(streamFrame);
4707     }
4708     if (dialog.exec() == QDialog::Accepted) {
4709         // import selected streams
4710         for (int i = 0; i < groupList.count(); i++) {
4711             if (groupList.at(i)->isChecked()) {
4712                 int vindex = groupList.at(i)->property("vindex").toInt();
4713                 int aindex = comboList.at(i)->itemData(comboList.at(i)->currentIndex()).toInt();
4714                 data.insert("video_index", QString::number(vindex));
4715                 data.insert("audio_index", QString::number(aindex));
4716                 data.insert("bypassDuplicate", "1");
4717                 emit addClip(KUrl(path), data);
4718             }
4719         }
4720     }
4721 }
4722
4723 #include "renderer.moc"
4724