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