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