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