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