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