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