]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Fix play / pause: http://kdenlive.org/mantis/view.php?id=2317
[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     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1546 }
1547
1548 void Render::switchPlay(bool play)
1549 {
1550     QMutexLocker locker(&m_mutex);
1551     requestedSeekPosition = SEEK_INACTIVE;
1552     if (!m_mltProducer || !m_mltConsumer)
1553         return;
1554     if (m_isZoneMode) resetZoneMode();
1555     if (play && m_paused) {
1556         if (m_name == Kdenlive::clipMonitor && m_mltConsumer->position() == m_mltProducer->get_out()) m_mltProducer->seek(0);
1557         m_paused = false;
1558         if (m_mltConsumer->is_stopped()) {
1559             m_mltConsumer->start();
1560         }
1561         m_mltProducer->set_speed(1.0);
1562         m_mltConsumer->set("refresh", 1);
1563     } else if (!play) {
1564         m_paused = true;
1565         m_mltProducer->set_speed(0.0);
1566         m_mltConsumer->set("refresh", 0);
1567         m_mltProducer->seek(m_mltConsumer->position());
1568         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1569         if (m_isZoneMode) resetZoneMode();
1570
1571         //emitConsumerStopped();
1572         /*m_mltConsumer->set("refresh", 0);
1573         m_mltConsumer->stop();
1574         m_mltConsumer->purge();
1575         m_mltProducer->set_speed(0.0);
1576         //m_framePosition = m_mltProducer->position();
1577         m_mltProducer->seek(m_framePosition);
1578         emit rendererPosition(m_framePosition);*/
1579     }
1580 }
1581
1582 void Render::play(double speed)
1583 {
1584     requestedSeekPosition = SEEK_INACTIVE;
1585     if (!m_mltProducer) return;
1586     double current_speed = m_mltProducer->get_speed(); 
1587     if (current_speed == speed) return;
1588     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1589     m_mltProducer->set_speed(speed);
1590     if (m_mltConsumer->is_stopped() && speed != 0) {
1591         m_mltConsumer->start();
1592     }
1593     m_paused = speed == 0;
1594     if (current_speed == 0 && speed != 0) m_mltConsumer->set("refresh", 1);
1595 }
1596
1597 void Render::play(const GenTime & startTime)
1598 {
1599     requestedSeekPosition = SEEK_INACTIVE;
1600     if (!m_mltProducer || !m_mltConsumer)
1601         return;
1602     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1603     m_mltProducer->set_speed(1.0);
1604     m_mltConsumer->set("refresh", 1);
1605 }
1606
1607 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime)
1608 {
1609     requestedSeekPosition = SEEK_INACTIVE;
1610     if (!m_mltProducer || !m_mltConsumer)
1611         return;
1612     //m_mltProducer->set("eof", "loop");
1613     m_isLoopMode = true;
1614     m_loopStart = startTime;
1615     playZone(startTime, stopTime);
1616 }
1617
1618 void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
1619 {
1620     requestedSeekPosition = SEEK_INACTIVE;
1621     if (!m_mltProducer || !m_mltConsumer)
1622         return;
1623     if (!m_isZoneMode) m_originalOut = m_mltProducer->get_playtime() - 1;
1624     m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
1625     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1626     m_mltProducer->set_speed(1.0);
1627     m_mltConsumer->set("refresh", 1);
1628     if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1629     m_isZoneMode = true;
1630 }
1631
1632 void Render::resetZoneMode()
1633 {
1634     if (!m_mltProducer || (!m_isZoneMode && !m_isLoopMode)) return;
1635     m_mltProducer->set("out", m_originalOut);
1636     //m_mltProducer->set("eof", "pause");
1637     m_isZoneMode = false;
1638     m_isLoopMode = false;
1639 }
1640
1641 void Render::seekToFrame(int pos)
1642 {
1643     resetZoneMode();
1644     seek(pos);
1645 }
1646
1647 void Render::seekToFrameDiff(int diff)
1648 {
1649     resetZoneMode();
1650     if (requestedSeekPosition == SEEK_INACTIVE)
1651         seek(m_mltProducer->position() + diff);
1652     else seek(requestedSeekPosition + diff);
1653 }
1654
1655 void Render::refreshIfActive()
1656 {
1657     if (!m_mltConsumer->is_stopped() && m_mltProducer && m_paused) m_refreshTimer.start();
1658 }
1659
1660 void Render::doRefresh()
1661 {
1662     if (m_mltProducer && m_paused) m_refreshTimer.start();
1663 }
1664
1665 void Render::refresh()
1666 {
1667     QMutexLocker locker(&m_mutex);
1668     if (!m_mltProducer)
1669         return;
1670     if (m_mltConsumer) {
1671         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1672         m_paused = false;
1673         //m_mltConsumer->purge();
1674         m_mltConsumer->set("refresh", 1);
1675     }
1676 }
1677
1678 void Render::setDropFrames(bool show)
1679 {
1680     QMutexLocker locker(&m_mutex);
1681     if (m_mltConsumer) {
1682         int dropFrames = KdenliveSettings::mltthreads();
1683         if (show == false) dropFrames = -dropFrames;
1684         m_mltConsumer->stop();
1685         if (m_winid == 0)
1686             m_mltConsumer->set("real_time", dropFrames);
1687         else
1688             m_mltConsumer->set("play.real_time", dropFrames);
1689
1690         if (m_mltConsumer->start() == -1) {
1691             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1692         }
1693
1694     }
1695 }
1696
1697 bool Render::isPlaying() const
1698 {
1699     if (!m_mltConsumer || m_mltConsumer->is_stopped()) return false;
1700     return !m_paused;
1701 }
1702
1703 double Render::playSpeed() const
1704 {
1705     if (m_mltProducer) return m_mltProducer->get_speed();
1706     return 0.0;
1707 }
1708
1709 GenTime Render::seekPosition() const
1710 {
1711     if (m_mltConsumer) return GenTime((int) m_mltConsumer->position(), m_fps);
1712     //if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1713     else return GenTime();
1714 }
1715
1716 int Render::seekFramePosition() const
1717 {
1718     //if (m_mltProducer) return (int) m_mltProducer->position();
1719     if (m_mltConsumer) return (int) m_mltConsumer->position();
1720     return 0;
1721 }
1722
1723 void Render::emitFrameUpdated(Mlt::Frame& frame)
1724 {
1725     mlt_image_format format = mlt_image_rgb24a;
1726     int width = 0;
1727     int height = 0;
1728     const uchar* image = frame.get_image(format, width, height);
1729     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1730     memcpy(qimage.scanLine(0), image, width * height * 4);
1731     emit frameUpdated(qimage.rgbSwapped());
1732 }
1733
1734 void Render::emitFrameNumber()
1735 {
1736     int currentPos = m_mltConsumer->position();
1737     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1738     emit rendererPosition(currentPos);
1739     if (requestedSeekPosition != SEEK_INACTIVE) {
1740         m_mltProducer->seek(requestedSeekPosition);
1741         if (m_paused) {
1742             refresh();
1743         }
1744         requestedSeekPosition = SEEK_INACTIVE;
1745     }
1746 }
1747
1748 void Render::emitConsumerStopped()
1749 {
1750     // This is used to know when the playing stopped
1751     if (m_mltProducer) {
1752         double pos = m_mltProducer->position();
1753         m_paused = true;
1754         if (m_isLoopMode) play(m_loopStart);
1755         //else if (m_isZoneMode) resetZoneMode();
1756         emit rendererStopped((int) pos);
1757     }
1758 }
1759
1760 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1761 {
1762     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1763 }
1764
1765 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
1766 {
1767     if (!m_mltProducer) {
1768         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1769         return;
1770     }
1771
1772     //int height = 1080;//KdenliveSettings::defaultheight();
1773     //int width = 1940; //KdenliveSettings::displaywidth();
1774     //TODO: rewrite
1775     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1776     /*
1777        QPixmap pix(width, height);
1778        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1779        m_convert.set("forced", mlt_image_rgb24a);
1780        m_mltProducer->attach(m_convert);
1781        Mlt::Frame * frame = m_mltProducer->get_frame();
1782        m_mltProducer->detach(m_convert);
1783        if (frame) {
1784            pix = frameThumbnail(frame, width, height);
1785            delete frame;
1786        }*/
1787     pix.save(url.path(), "PNG");
1788     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1789 }
1790
1791
1792 void Render::showFrame(Mlt::Frame& frame)
1793 {
1794     int currentPos = m_mltConsumer->position();
1795     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1796     emit rendererPosition(currentPos);
1797     if (frame.is_valid()) {
1798         mlt_image_format format = mlt_image_rgb24a;
1799         int width = 0;
1800         int height = 0;
1801         const uchar* image = frame.get_image(format, width, height);
1802         QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1803         memcpy(qimage.scanLine(0), image, width * height * 4);
1804         emit showImageSignal(qimage);
1805         if (analyseAudio) showAudio(frame);
1806         if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
1807             emit frameUpdated(qimage.rgbSwapped());
1808         }
1809     }
1810     emit checkSeeking();
1811 }
1812
1813 void Render::slotCheckSeeking()
1814 {
1815       if (requestedSeekPosition != SEEK_INACTIVE) {
1816         m_mltProducer->seek(requestedSeekPosition);
1817         if (m_paused) {
1818             refresh();
1819         }
1820     }
1821 }
1822
1823 void Render::disablePreview(bool disable)
1824 {
1825     if (m_mltConsumer) {
1826         m_mltConsumer->stop();
1827         m_mltConsumer->set("preview_off", (int) disable);
1828         m_mltConsumer->set("refresh", 0);
1829         m_mltConsumer->start();
1830     }
1831 }
1832
1833 void Render::showAudio(Mlt::Frame& frame)
1834 {
1835     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1836         return;
1837     }
1838     mlt_audio_format audio_format = mlt_audio_s16;
1839     //FIXME: should not be hardcoded..
1840     int freq = 48000;
1841     int num_channels = 2;
1842     int samples = 0;
1843     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1844
1845     if (!data) {
1846         return;
1847     }
1848
1849     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1850     // So the vector is of size samples*channels.
1851     QVector<int16_t> sampleVector(samples*num_channels);
1852     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1853
1854     if (samples > 0) {
1855         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1856     }
1857 }
1858
1859 /*
1860  * MLT playlist direct manipulation.
1861  */
1862
1863 void Render::mltCheckLength(Mlt::Tractor *tractor)
1864 {
1865     //kDebug()<<"checking track length: "<<track<<"..........";
1866
1867     int trackNb = tractor->count();
1868     int duration = 0;
1869     int trackDuration;
1870     if (trackNb == 1) {
1871         Mlt::Producer trackProducer(tractor->track(0));
1872         duration = trackProducer.get_playtime() - 1;
1873         m_mltProducer->set("out", duration);
1874         emit durationChanged(duration);
1875         return;
1876     }
1877     while (trackNb > 1) {
1878         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1879         trackDuration = trackProducer.get_playtime() - 1;
1880         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1881         if (trackDuration > duration) duration = trackDuration;
1882         trackNb--;
1883     }
1884
1885     Mlt::Producer blackTrackProducer(tractor->track(0));
1886
1887     if (blackTrackProducer.get_playtime() - 1 != duration) {
1888         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1889         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1890         if (blackclip && blackclip->is_blank()) {
1891             delete blackclip;
1892             blackclip = NULL;
1893         }
1894
1895         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
1896             if (blackclip) delete blackclip;
1897             blackTrackPlaylist.clear();
1898             m_blackClip->set("length", duration + 1);
1899             m_blackClip->set("out", duration);
1900             blackclip = m_blackClip->cut(0, duration);
1901             blackTrackPlaylist.insert_at(0, blackclip, 1);
1902         } else {
1903             if (duration > blackclip->parent().get_length()) {
1904                 blackclip->parent().set("length", duration + 1);
1905                 blackclip->parent().set("out", duration);
1906                 blackclip->set("length", duration + 1);
1907             }
1908             blackTrackPlaylist.resize_clip(0, 0, duration);
1909         }
1910
1911         delete blackclip;
1912         m_mltProducer->set("out", duration);
1913         emit durationChanged(duration);
1914     }
1915 }
1916
1917 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
1918 {
1919     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
1920     QLocale locale;
1921     // We want a slowmotion producer
1922     double speed = element.attribute("speed", "1.0").toDouble();
1923     int strobe = element.attribute("strobe", "1").toInt();
1924     QString url = QString::fromUtf8(prod->get("resource"));
1925     url.append('?' + locale.toString(speed));
1926     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
1927     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1928     if (!slowprod || slowprod->get_producer() == NULL) {
1929         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
1930         if (strobe > 1) slowprod->set("strobe", strobe);
1931         QString id = prod->parent().get("id");
1932         if (id.contains('_')) id = id.section('_', 0, 0);
1933         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
1934         if (strobe > 1) producerid.append(':' + QString::number(strobe));
1935         slowprod->set("id", producerid.toUtf8().constData());
1936         m_slowmotionProducers.insert(url, slowprod);
1937     }
1938     return slowprod;
1939 }
1940
1941 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
1942 {
1943     m_refreshTimer.stop();
1944     if (m_mltProducer == NULL) {
1945         kDebug() << "PLAYLIST NOT INITIALISED //////";
1946         return -1;
1947     }
1948     if (prod == NULL) {
1949         kDebug() << "Cannot insert clip without producer //////";
1950         return -1;
1951     }
1952     Mlt::Producer parentProd(m_mltProducer->parent());
1953     if (parentProd.get_producer() == NULL) {
1954         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1955         return -1;
1956     }
1957
1958     Mlt::Service service(parentProd.get_service());
1959     if (service.type() != tractor_type) {
1960         kWarning() << "// TRACTOR PROBLEM";
1961         return -1;
1962     }
1963     Mlt::Tractor tractor(service);
1964     if (info.track > tractor.count() - 1) {
1965         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
1966         return -1;
1967     }
1968     service.lock();
1969     Mlt::Producer trackProducer(tractor.track(info.track));
1970     int trackDuration = trackProducer.get_playtime() - 1;
1971     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1972     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
1973     prod = checkSlowMotionProducer(prod, element);
1974     if (prod == NULL || !prod->is_valid()) {
1975         service.unlock();
1976         return -1;
1977     }
1978
1979     int cutPos = (int) info.cropStart.frames(m_fps);
1980     if (cutPos < 0) cutPos = 0;
1981     int insertPos = (int) info.startPos.frames(m_fps);
1982     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
1983     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
1984     if (overwrite && (insertPos < trackDuration)) {
1985         // Replace zone with blanks
1986         //trackPlaylist.split_at(insertPos, true);
1987         trackPlaylist.remove_region(insertPos, cutDuration + 1);
1988         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1989         trackPlaylist.insert_blank(clipIndex, cutDuration);
1990     } else if (push) {
1991         trackPlaylist.split_at(insertPos, true);
1992         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1993         trackPlaylist.insert_blank(clipIndex, cutDuration);
1994     }
1995     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
1996     delete clip;
1997     /*if (QString(prod->get("transparency")).toInt() == 1)
1998         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
1999
2000     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
2001     service.unlock();
2002     /*tractor.multitrack()->refresh();
2003     tractor.refresh();*/
2004     return 0;
2005 }
2006
2007
2008 bool Render::mltCutClip(int track, GenTime position)
2009 {
2010     Mlt::Service service(m_mltProducer->parent().get_service());
2011     if (service.type() != tractor_type) {
2012         kWarning() << "// TRACTOR PROBLEM";
2013         return false;
2014     }
2015
2016     Mlt::Tractor tractor(service);
2017     Mlt::Producer trackProducer(tractor.track(track));
2018     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2019
2020
2021     /* // Display playlist info
2022     kDebug()<<"////////////  BEFORE";
2023     for (int i = 0; i < trackPlaylist.count(); i++) {
2024     int blankStart = trackPlaylist.clip_start(i);
2025     int blankDuration = trackPlaylist.clip_length(i) - 1;
2026     QString blk;
2027     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2028     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2029     }*/
2030
2031     int cutPos = (int) position.frames(m_fps);
2032
2033     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
2034     if (trackPlaylist.is_blank(clipIndex)) {
2035         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
2036         return false;
2037     }
2038     service.lock();
2039     int clipStart = trackPlaylist.clip_start(clipIndex);
2040     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
2041     service.unlock();
2042
2043     // duplicate effects
2044     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
2045     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
2046     
2047     if (original == NULL || clip == NULL) {
2048         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
2049         return false;
2050     }
2051
2052     Mlt::Service clipService(original->get_service());
2053     Mlt::Service dupService(clip->get_service());
2054
2055
2056     delete original;
2057     delete clip;
2058     int ct = 0;
2059     Mlt::Filter *filter = clipService.filter(ct);
2060     while (filter) {
2061         // Only duplicate Kdenlive filters, and skip the fade in effects
2062         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
2063             // looks like there is no easy way to duplicate a filter,
2064             // so we will create a new one and duplicate its properties
2065             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
2066             if (dup && dup->is_valid()) {
2067                 Mlt::Properties entries(filter->get_properties());
2068                 for (int i = 0; i < entries.count(); i++) {
2069                     dup->set(entries.get_name(i), entries.get(i));
2070                 }
2071                 dupService.attach(*dup);
2072             }
2073         }
2074         ct++;
2075         filter = clipService.filter(ct);
2076     }
2077     return true;
2078     /* // Display playlist info
2079     kDebug()<<"////////////  AFTER";
2080     for (int i = 0; i < trackPlaylist.count(); i++) {
2081     int blankStart = trackPlaylist.clip_start(i);
2082     int blankDuration = trackPlaylist.clip_length(i) - 1;
2083     QString blk;
2084     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2085     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2086     }*/
2087
2088 }
2089
2090 Mlt::Tractor *Render::lockService()
2091 {
2092     // we are going to replace some clips, purge consumer
2093     if (!m_mltProducer) return NULL;
2094     QMutexLocker locker(&m_mutex);
2095     if (m_mltConsumer) {
2096         m_mltConsumer->purge();
2097     }
2098     Mlt::Service service(m_mltProducer->parent().get_service());
2099     if (service.type() != tractor_type) {
2100         return NULL;
2101     }
2102     service.lock();
2103     return new Mlt::Tractor(service);
2104
2105 }
2106
2107 void Render::unlockService(Mlt::Tractor *tractor)
2108 {
2109     if (tractor) {
2110         delete tractor;
2111     }
2112     if (!m_mltProducer) return;
2113     Mlt::Service service(m_mltProducer->parent().get_service());
2114     if (service.type() != tractor_type) {
2115         kWarning() << "// TRACTOR PROBLEM";
2116         return;
2117     }
2118     service.unlock();
2119 }
2120
2121 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
2122 {
2123     // TODO: optimize
2124     if (prod == NULL || tractor == NULL) {
2125         kDebug() << "Cannot update clip with null producer //////";
2126         return false;
2127     }
2128
2129     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
2130     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2131     int startPos = info.startPos.frames(m_fps);
2132     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2133     if (trackPlaylist.is_blank(clipIndex)) {
2134         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
2135         return false;
2136     }
2137     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2138     // keep effects
2139     QList <Mlt::Filter *> filtersList;
2140     Mlt::Service sourceService(clip->get_service());
2141     int ct = 0;
2142     Mlt::Filter *filter = sourceService.filter(ct);
2143     while (filter) {
2144         if (filter->get_int("kdenlive_ix") != 0) {
2145             filtersList.append(filter);
2146         }
2147         ct++;
2148         filter = sourceService.filter(ct);
2149     }
2150     delete clip;
2151     clip = trackPlaylist.replace_with_blank(clipIndex);
2152     delete clip;
2153     prod = checkSlowMotionProducer(prod, element);
2154     if (prod == NULL || !prod->is_valid()) {
2155         return false;
2156     }
2157
2158     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
2159     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
2160     Mlt::Service destService(clip2->get_service());
2161     delete clip2;
2162
2163     if (!filtersList.isEmpty()) {
2164         for (int i = 0; i < filtersList.count(); i++)
2165             destService.attach(*(filtersList.at(i)));
2166     }
2167     return true;
2168 }
2169
2170
2171 bool Render::mltRemoveClip(int track, GenTime position)
2172 {
2173     m_refreshTimer.stop();
2174     Mlt::Service service(m_mltProducer->parent().get_service());
2175     if (service.type() != tractor_type) {
2176         kWarning() << "// TRACTOR PROBLEM";
2177         return false;
2178     }
2179     //service.lock();
2180     Mlt::Tractor tractor(service);
2181     Mlt::Producer trackProducer(tractor.track(track));
2182     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2183     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2184
2185     if (trackPlaylist.is_blank(clipIndex)) {
2186         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
2187         //service.unlock();
2188         return false;
2189     }
2190     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2191     if (clip) delete clip;
2192     trackPlaylist.consolidate_blanks(0);
2193
2194     /* // Display playlist info
2195     kDebug()<<"////  AFTER";
2196     for (int i = 0; i < trackPlaylist.count(); i++) {
2197     int blankStart = trackPlaylist.clip_start(i);
2198     int blankDuration = trackPlaylist.clip_length(i) - 1;
2199     QString blk;
2200     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2201     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2202     }*/
2203     //service.unlock();
2204     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
2205     return true;
2206 }
2207
2208 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
2209 {
2210     if (!m_mltProducer) {
2211         kDebug() << "PLAYLIST NOT INITIALISED //////";
2212         return 0;
2213     }
2214     Mlt::Producer parentProd(m_mltProducer->parent());
2215     if (parentProd.get_producer() == NULL) {
2216         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2217         return 0;
2218     }
2219
2220     Mlt::Service service(parentProd.get_service());
2221     Mlt::Tractor tractor(service);
2222     int insertPos = pos.frames(m_fps);
2223
2224     Mlt::Producer trackProducer(tractor.track(track));
2225     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2226     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2227     if (clipIndex == trackPlaylist.count()) {
2228         // We are after the end of the playlist
2229         return -1;
2230     }
2231     if (!trackPlaylist.is_blank(clipIndex)) return 0;
2232     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
2233     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
2234 }
2235
2236 int Render::mltTrackDuration(int track)
2237 {
2238     if (!m_mltProducer) {
2239         kDebug() << "PLAYLIST NOT INITIALISED //////";
2240         return -1;
2241     }
2242     Mlt::Producer parentProd(m_mltProducer->parent());
2243     if (parentProd.get_producer() == NULL) {
2244         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2245         return -1;
2246     }
2247
2248     Mlt::Service service(parentProd.get_service());
2249     Mlt::Tractor tractor(service);
2250
2251     Mlt::Producer trackProducer(tractor.track(track));
2252     return trackProducer.get_playtime() - 1;
2253 }
2254
2255 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
2256 {
2257     if (!m_mltProducer) {
2258         kDebug() << "PLAYLIST NOT INITIALISED //////";
2259         return;
2260     }
2261     Mlt::Producer parentProd(m_mltProducer->parent());
2262     if (parentProd.get_producer() == NULL) {
2263         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2264         return;
2265     }
2266     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
2267     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
2268
2269     Mlt::Service service(parentProd.get_service());
2270     Mlt::Tractor tractor(service);
2271     service.lock();
2272     int diff = duration.frames(m_fps);
2273     int offset = timeOffset.frames(m_fps);
2274     int insertPos;
2275
2276     if (track != -1) {
2277         // insert space in one track only
2278         Mlt::Producer trackProducer(tractor.track(track));
2279         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2280         insertPos = trackClipStartList.value(track);
2281         if (insertPos != -1) {
2282             insertPos += offset;
2283             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2284             if (diff > 0) {
2285                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2286             } else {
2287                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2288                 if (!trackPlaylist.is_blank(clipIndex)) {
2289                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2290                 }
2291                 int position = trackPlaylist.clip_start(clipIndex);
2292                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2293                 if (blankDuration + diff == 0) {
2294                     trackPlaylist.remove(clipIndex);
2295                 } else trackPlaylist.remove_region(position, -diff);
2296             }
2297             trackPlaylist.consolidate_blanks(0);
2298         }
2299         // now move transitions
2300         mlt_service serv = m_mltProducer->parent().get_service();
2301         mlt_service nextservice = mlt_service_get_producer(serv);
2302         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2303         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2304         QString resource = mlt_properties_get(properties, "mlt_service");
2305
2306         while (mlt_type == "transition") {
2307             mlt_transition tr = (mlt_transition) nextservice;
2308             int currentTrack = mlt_transition_get_b_track(tr);
2309             int currentIn = (int) mlt_transition_get_in(tr);
2310             int currentOut = (int) mlt_transition_get_out(tr);
2311             insertPos = trackTransitionStartList.value(track);
2312             if (insertPos != -1) {
2313                 insertPos += offset;
2314                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2315                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2316                 }
2317             }
2318             nextservice = mlt_service_producer(nextservice);
2319             if (nextservice == NULL) break;
2320             properties = MLT_SERVICE_PROPERTIES(nextservice);
2321             mlt_type = mlt_properties_get(properties, "mlt_type");
2322             resource = mlt_properties_get(properties, "mlt_service");
2323         }
2324     } else {
2325         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2326             Mlt::Producer trackProducer(tractor.track(trackNb));
2327             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2328
2329             //int clipNb = trackPlaylist.count();
2330             insertPos = trackClipStartList.value(trackNb);
2331             if (insertPos != -1) {
2332                 insertPos += offset;
2333
2334                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2335                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2336                         for (int i = 0; i < clipNb; i++) {
2337                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2338                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2339                      kDebug()<<"-------------";
2340                  }
2341                  kDebug()<<"END-------------";*/
2342
2343
2344                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2345                 if (diff > 0) {
2346                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2347                 } else {
2348                     if (!trackPlaylist.is_blank(clipIndex)) {
2349                         clipIndex --;
2350                     }
2351                     if (!trackPlaylist.is_blank(clipIndex)) {
2352                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2353                     }
2354                     int position = trackPlaylist.clip_start(clipIndex);
2355                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2356                     if (diff + blankDuration == 0) {
2357                         trackPlaylist.remove(clipIndex);
2358                     } else trackPlaylist.remove_region(position, - diff);
2359                 }
2360                 trackPlaylist.consolidate_blanks(0);
2361             }
2362         }
2363         // now move transitions
2364         mlt_service serv = m_mltProducer->parent().get_service();
2365         mlt_service nextservice = mlt_service_get_producer(serv);
2366         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2367         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2368         QString resource = mlt_properties_get(properties, "mlt_service");
2369
2370         while (mlt_type == "transition") {
2371             mlt_transition tr = (mlt_transition) nextservice;
2372             int currentIn = (int) mlt_transition_get_in(tr);
2373             int currentOut = (int) mlt_transition_get_out(tr);
2374             int currentTrack = mlt_transition_get_b_track(tr);
2375             insertPos = trackTransitionStartList.value(currentTrack);
2376             if (insertPos != -1) {
2377                 insertPos += offset;
2378                 if (currentOut > insertPos && resource != "mix") {
2379                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2380                 }
2381             }
2382             nextservice = mlt_service_producer(nextservice);
2383             if (nextservice == NULL) break;
2384             properties = MLT_SERVICE_PROPERTIES(nextservice);
2385             mlt_type = mlt_properties_get(properties, "mlt_type");
2386             resource = mlt_properties_get(properties, "mlt_service");
2387         }
2388     }
2389     service.unlock();
2390     mltCheckLength(&tractor);
2391     m_mltConsumer->set("refresh", 1);
2392 }
2393
2394
2395 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2396 {
2397     if (source == dest) return;
2398     Mlt::Service sourceService(source->get_service());
2399     Mlt::Service destService(dest->get_service());
2400
2401     // move all effects to the correct producer
2402     int ct = 0;
2403     Mlt::Filter *filter = sourceService.filter(ct);
2404     while (filter) {
2405         if (filter->get_int("kdenlive_ix") != 0) {
2406             sourceService.detach(*filter);
2407             destService.attach(*filter);
2408         } else ct++;
2409         filter = sourceService.filter(ct);
2410     }
2411 }
2412
2413 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2414 {
2415     int newLength = 0;
2416     Mlt::Service service(m_mltProducer->parent().get_service());
2417     if (service.type() != tractor_type) {
2418         kWarning() << "// TRACTOR PROBLEM";
2419         return -1;
2420     }
2421
2422     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2423     Mlt::Tractor tractor(service);
2424     Mlt::Producer trackProducer(tractor.track(info.track));
2425     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2426     int startPos = info.startPos.frames(m_fps);
2427     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2428     int clipLength = trackPlaylist.clip_length(clipIndex);
2429
2430     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2431     if (original == NULL) {
2432         return -1;
2433     }
2434     if (!original->is_valid() || original->is_blank()) {
2435         // invalid clip
2436         delete original;
2437         return -1;
2438     }
2439     Mlt::Producer clipparent = original->parent();
2440     if (!clipparent.is_valid() || clipparent.is_blank()) {
2441         // invalid clip
2442         delete original;
2443         return -1;
2444     }
2445
2446     QString serv = clipparent.get("mlt_service");
2447     QString id = clipparent.get("id");
2448     if (speed <= 0 && speed > -1) speed = 1.0;
2449     //kDebug() << "CLIP SERVICE: " << serv;
2450     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2451         service.lock();
2452         QString url = QString::fromUtf8(clipparent.get("resource"));
2453         url.append('?' + m_locale.toString(speed));
2454         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2455         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2456         if (!slowprod || slowprod->get_producer() == NULL) {
2457             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2458             if (strobe > 1) slowprod->set("strobe", strobe);
2459             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2460             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2461             slowprod->set("id", producerid.toUtf8().constData());
2462             // copy producer props
2463             double ar = original->parent().get_double("force_aspect_ratio");
2464             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2465             double fps = original->parent().get_double("force_fps");
2466             if (fps != 0.0) slowprod->set("force_fps", fps);
2467             int threads = original->parent().get_int("threads");
2468             if (threads != 0) slowprod->set("threads", threads);
2469             if (original->parent().get("force_progressive"))
2470                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2471             if (original->parent().get("force_tff"))
2472                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2473             int ix = original->parent().get_int("video_index");
2474             if (ix != 0) slowprod->set("video_index", ix);
2475             int colorspace = original->parent().get_int("force_colorspace");
2476             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2477             int full_luma = original->parent().get_int("set.force_full_luma");
2478             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2479             m_slowmotionProducers.insert(url, slowprod);
2480         }
2481         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2482         trackPlaylist.consolidate_blanks(0);
2483
2484         // Check that the blank space is long enough for our new duration
2485         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2486         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2487         Mlt::Producer *cut;
2488         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2489             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2490             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2491         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2492
2493         // move all effects to the correct producer
2494         mltPasteEffects(clip, cut);
2495         trackPlaylist.insert_at(startPos, cut, 1);
2496         delete cut;
2497         delete clip;
2498         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2499         newLength = trackPlaylist.clip_length(clipIndex);
2500         service.unlock();
2501     } else if (speed == 1.0 && strobe < 2) {
2502         service.lock();
2503
2504         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2505         trackPlaylist.consolidate_blanks(0);
2506
2507         // Check that the blank space is long enough for our new duration
2508         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2509         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2510
2511         Mlt::Producer *cut;
2512         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2513         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2514             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2515             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2516         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2517
2518         // move all effects to the correct producer
2519         mltPasteEffects(clip, cut);
2520
2521         trackPlaylist.insert_at(startPos, cut, 1);
2522         delete cut;
2523         delete clip;
2524         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2525         newLength = trackPlaylist.clip_length(clipIndex);
2526         service.unlock();
2527
2528     } else if (serv == "framebuffer") {
2529         service.lock();
2530         QString url = QString::fromUtf8(clipparent.get("resource"));
2531         url = url.section('?', 0, 0);
2532         url.append('?' + m_locale.toString(speed));
2533         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2534         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2535         if (!slowprod || slowprod->get_producer() == NULL) {
2536             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2537             slowprod->set("strobe", strobe);
2538             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2539             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2540             slowprod->set("id", producerid.toUtf8().constData());
2541             // copy producer props
2542             double ar = original->parent().get_double("force_aspect_ratio");
2543             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2544             double fps = original->parent().get_double("force_fps");
2545             if (fps != 0.0) slowprod->set("force_fps", fps);
2546             if (original->parent().get("force_progressive"))
2547                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2548             if (original->parent().get("force_tff"))
2549                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2550             int threads = original->parent().get_int("threads");
2551             if (threads != 0) slowprod->set("threads", threads);
2552             int ix = original->parent().get_int("video_index");
2553             if (ix != 0) slowprod->set("video_index", ix);
2554             int colorspace = original->parent().get_int("force_colorspace");
2555             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2556             int full_luma = original->parent().get_int("set.force_full_luma");
2557             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2558             m_slowmotionProducers.insert(url, slowprod);
2559         }
2560         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2561         trackPlaylist.consolidate_blanks(0);
2562
2563         GenTime duration = speedIndependantInfo.cropDuration / speed;
2564         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2565
2566         // Check that the blank space is long enough for our new duration
2567         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2568         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2569
2570         Mlt::Producer *cut;
2571         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2572             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2573             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2574         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2575
2576         // move all effects to the correct producer
2577         mltPasteEffects(clip, cut);
2578
2579         trackPlaylist.insert_at(startPos, cut, 1);
2580         delete cut;
2581         delete clip;
2582         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2583         newLength = trackPlaylist.clip_length(clipIndex);
2584
2585         service.unlock();
2586     }
2587     delete original;
2588     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2589     return newLength;
2590 }
2591
2592 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2593 {
2594     Mlt::Service service(m_mltProducer->parent().get_service());
2595     bool success = false;
2596     Mlt::Tractor tractor(service);
2597     Mlt::Producer trackProducer(tractor.track(track));
2598     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2599     Mlt::Service clipService(trackPlaylist.get_service());
2600
2601     service.lock();
2602     int ct = 0;
2603     Mlt::Filter *filter = clipService.filter(ct);
2604     while (filter) {
2605         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2606             if (clipService.detach(*filter) == 0) success = true;
2607         } else if (updateIndex) {
2608             // Adjust the other effects index
2609             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2610             ct++;
2611         } else ct++;
2612         filter = clipService.filter(ct);
2613     }
2614     service.unlock();
2615     refresh();
2616     return success;
2617 }
2618
2619 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2620 {
2621     if (position < GenTime()) {
2622         // Remove track effect
2623         return mltRemoveTrackEffect(track, index, updateIndex);
2624     }
2625     Mlt::Service service(m_mltProducer->parent().get_service());
2626     bool success = false;
2627     Mlt::Tractor tractor(service);
2628     Mlt::Producer trackProducer(tractor.track(track));
2629     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2630
2631     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2632     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2633     if (!clip) {
2634         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2635         return false;
2636     }
2637
2638     Mlt::Service clipService(clip->get_service());
2639     int duration = clip->get_playtime();
2640     if (doRefresh) {
2641         // Check if clip is visible in monitor
2642         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2643         if (diff < 0 || diff > duration) doRefresh = false;
2644     }
2645     delete clip;
2646
2647     service.lock();
2648     int ct = 0;
2649     Mlt::Filter *filter = clipService.filter(ct);
2650     while (filter) {
2651         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2652             if (clipService.detach(*filter) == 0) success = true;
2653             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2654         } else if (updateIndex) {
2655             // Adjust the other effects index
2656             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2657             ct++;
2658         } else ct++;
2659         filter = clipService.filter(ct);
2660     }
2661     service.unlock();
2662     if (doRefresh) refresh();
2663     return success;
2664 }
2665
2666 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2667 {
2668     Mlt::Service service(m_mltProducer->parent().get_service());
2669     Mlt::Tractor tractor(service);
2670     Mlt::Producer trackProducer(tractor.track(track));
2671     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2672     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2673     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2674 }
2675
2676
2677 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2678 {
2679
2680     Mlt::Service service(m_mltProducer->parent().get_service());
2681
2682     Mlt::Tractor tractor(service);
2683     Mlt::Producer trackProducer(tractor.track(track));
2684     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2685
2686     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2687     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2688     if (!clip) {
2689         return false;
2690     }
2691
2692     Mlt::Service clipService(clip->get_service());
2693     int duration = clip->get_playtime();
2694     if (doRefresh) {
2695         // Check if clip is visible in monitor
2696         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2697         if (diff < 0 || diff > duration) doRefresh = false;
2698     }
2699     delete clip;
2700     return mltAddEffect(clipService, params, duration, doRefresh);
2701 }
2702
2703 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2704 {
2705     bool updateIndex = false;
2706     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2707     int ct = 0;
2708     service.lock();
2709
2710     Mlt::Filter *filter = service.filter(ct);
2711     while (filter) {
2712         if (filter->get_int("kdenlive_ix") == filter_ix) {
2713             // A filter at that position already existed, so we will increase all indexes later
2714             updateIndex = true;
2715             break;
2716         }
2717         ct++;
2718         filter = service.filter(ct);
2719     }
2720
2721     if (params.paramValue("id") == "speed") {
2722         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2723         ct = 0;
2724         filter = service.filter(ct);
2725         while (filter) {
2726             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2727                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2728             }
2729             ct++;
2730             filter = service.filter(ct);
2731         }
2732         service.unlock();
2733         if (doRefresh) refresh();
2734         return true;
2735     }
2736
2737
2738     // temporarily remove all effects after insert point
2739     QList <Mlt::Filter *> filtersList;
2740     ct = 0;
2741     filter = service.filter(ct);
2742     while (filter) {
2743         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2744             filtersList.append(filter);
2745             service.detach(*filter);
2746         } else ct++;
2747         filter = service.filter(ct);
2748     }
2749
2750     addFilterToService(service, params, duration);
2751
2752     // re-add following filters
2753     for (int i = 0; i < filtersList.count(); i++) {
2754         Mlt::Filter *filter = filtersList.at(i);
2755         if (updateIndex)
2756             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2757         service.attach(*filter);
2758     }
2759     service.unlock();
2760     if (doRefresh) refresh();
2761     return true;
2762 }
2763
2764
2765 bool Render::addFilterToService(Mlt::Service service, EffectsParameterList params, int duration)
2766 {
2767       // create filter
2768     QString tag =  params.paramValue("tag");
2769     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2770     char *filterTag = qstrdup(tag.toUtf8().constData());
2771     char *filterId = qstrdup(params.paramValue("id").toUtf8().constData());
2772     QString kfr = params.paramValue("keyframes");
2773   if (!kfr.isEmpty()) {
2774         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2775         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2776         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2777         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2778         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2779         //double max = params.paramValue("max").toDouble();
2780         double min = params.paramValue("min").toDouble();
2781         double factor = params.paramValue("factor", "1").toDouble();
2782         double paramOffset = params.paramValue("offset", "0").toDouble();
2783         params.removeParam("starttag");
2784         params.removeParam("endtag");
2785         params.removeParam("keyframes");
2786         params.removeParam("min");
2787         params.removeParam("max");
2788         params.removeParam("factor");
2789         params.removeParam("offset");
2790         int offset = 0;
2791         // Special case, only one keyframe, means we want a constant value
2792         if (keyFrames.count() == 1) {
2793             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2794             if (filter && filter->is_valid()) {
2795                 filter->set("kdenlive_id", filterId);
2796                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2797                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2798                 for (int j = 0; j < params.count(); j++) {
2799                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2800                 }
2801                 filter->set("in", x1);
2802                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2803                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2804                 service.attach(*filter);
2805             }
2806         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2807                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2808                 if (filter && filter->is_valid()) {
2809                     filter->set("kdenlive_id", filterId);
2810                     int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2811                     double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2812                     int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2813                     double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2814                     if (x2 == -1) x2 = duration;
2815
2816                     for (int j = 0; j < params.count(); j++) {
2817                         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2818                     }
2819
2820                     filter->set("in", x1);
2821                     filter->set("out", x2);
2822                     //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2823                     filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2824                     filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2825                     service.attach(*filter);
2826                     offset = 1;
2827                 }
2828             }
2829         delete[] starttag;
2830         delete[] endtag;
2831     } else {
2832         Mlt::Filter *filter;
2833         QString prefix;
2834         filter = new Mlt::Filter(*m_mltProfile, filterTag);
2835         if (filter && filter->is_valid()) {
2836             filter->set("kdenlive_id", filterId);
2837         } else {
2838             kDebug() << "filter is NULL";
2839             service.unlock();
2840             return false;
2841         }
2842         params.removeParam("kdenlive_id");
2843         if (params.hasParam("_sync_in_out")) {
2844             // This effect must sync in / out with parent clip
2845             params.removeParam("_sync_in_out");
2846             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2847         }
2848
2849         for (int j = 0; j < params.count(); j++) {
2850             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2851         }
2852
2853         if (tag == "sox") {
2854             QString effectArgs = params.paramValue("id").section('_', 1);
2855
2856             params.removeParam("id");
2857             params.removeParam("kdenlive_ix");
2858             params.removeParam("tag");
2859             params.removeParam("disable");
2860             params.removeParam("region");
2861
2862             for (int j = 0; j < params.count(); j++) {
2863                 effectArgs.append(' ' + params.at(j).value());
2864             }
2865             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2866             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2867         }
2868         // attach filter to the clip
2869         service.attach(*filter);
2870     }
2871         
2872     delete[] filterId;
2873     delete[] filterTag;
2874     return true;
2875 }
2876
2877 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
2878 {
2879     Mlt::Service service(m_mltProducer->parent().get_service());
2880     Mlt::Tractor tractor(service);
2881     Mlt::Producer trackProducer(tractor.track(track));
2882     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2883     Mlt::Service clipService(trackPlaylist.get_service());
2884     int ct = 0;
2885     QString index = params.paramValue("kdenlive_ix");
2886     QString tag =  params.paramValue("tag");
2887
2888     Mlt::Filter *filter = clipService.filter(ct);
2889     while (filter) {
2890         if (filter->get_int("kdenlive_ix") == index.toInt()) {
2891             break;
2892         }
2893         ct++;
2894         filter = clipService.filter(ct);
2895     }
2896
2897     if (!filter) {
2898         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2899         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2900
2901         bool success = false;//mltAddTrackEffect(track, params);
2902         return success;
2903     }
2904     QString prefix;
2905     QString ser = filter->get("mlt_service");
2906     if (ser == "region") prefix = "filter0.";
2907     service.lock();
2908     for (int j = 0; j < params.count(); j++) {
2909         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2910     }
2911     service.unlock();
2912
2913     refresh();
2914     return true;
2915 }
2916
2917 bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList params)
2918 {
2919     int index = params.paramValue("kdenlive_ix").toInt();
2920     QString tag =  params.paramValue("tag");
2921
2922     if (!params.paramValue("keyframes").isEmpty() || (tag == "affine" && params.hasParam("background")) || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
2923         // This is a keyframe effect, to edit it, we remove it and re-add it.
2924         bool success = mltRemoveEffect(track, position, index, false);
2925 //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
2926         if (position < GenTime())
2927             success = mltAddTrackEffect(track, params);
2928         else
2929             success = mltAddEffect(track, position, params);
2930 //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
2931         return success;
2932     }
2933     if (position < GenTime()) {
2934         return mltEditTrackEffect(track, params);
2935     }
2936     // find filter
2937     Mlt::Service service(m_mltProducer->parent().get_service());
2938     Mlt::Tractor tractor(service);
2939     Mlt::Producer trackProducer(tractor.track(track));
2940     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2941
2942     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2943     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2944     if (!clip) {
2945         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2946         return false;
2947     }
2948
2949     int duration = clip->get_playtime();
2950     bool doRefresh = true;
2951     // Check if clip is visible in monitor
2952     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2953     if (diff < 0 || diff > duration)
2954         doRefresh = false;
2955     int ct = 0;
2956
2957     Mlt::Filter *filter = clip->filter(ct);
2958     while (filter) {
2959         if (filter->get_int("kdenlive_ix") == index) {
2960             break;
2961         }
2962         ct++;
2963         filter = clip->filter(ct);
2964     }
2965
2966     if (!filter) {
2967         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2968         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2969
2970         bool success = mltAddEffect(track, position, params);
2971         return success;
2972     }
2973     ct = 0;
2974     QString ser = filter->get("mlt_service");
2975     QList <Mlt::Filter *> filtersList;
2976     service.lock();
2977     if (ser != tag) {
2978         // Effect service changes, delete effect and re-add it
2979         clip->detach(*filter);  
2980         
2981         // Delete all effects after deleted one
2982         filter = clip->filter(ct);
2983         while (filter) {
2984             if (filter->get_int("kdenlive_ix") > index) {
2985                 filtersList.append(filter);
2986                 clip->detach(*filter);
2987             }
2988             else ct++;
2989             filter = clip->filter(ct);
2990         }
2991         
2992         // re-add filter
2993         addFilterToService(*clip, params, clip->get_playtime());
2994         delete clip;
2995         service.unlock();
2996
2997         if (doRefresh) refresh();
2998         return true;
2999     }
3000     if (params.hasParam("_sync_in_out")) {
3001         // This effect must sync in / out with parent clip
3002         params.removeParam("_sync_in_out");
3003         filter->set_in_and_out(clip->get_in(), clip->get_out());
3004     }
3005
3006     for (int j = 0; j < params.count(); j++) {
3007         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
3008     }
3009     
3010     for (int j = 0; j < filtersList.count(); j++) {
3011         clip->attach(*(filtersList.at(j)));
3012     }
3013
3014     delete clip;
3015     service.unlock();
3016
3017     if (doRefresh) refresh();
3018     return true;
3019 }
3020
3021 bool Render::mltEnableEffects(int track, GenTime position, QList <int> effectIndexes, bool disable)
3022 {
3023     if (position < GenTime()) {
3024         return mltEnableTrackEffects(track, effectIndexes, disable);
3025     }
3026     // find filter
3027     Mlt::Service service(m_mltProducer->parent().get_service());
3028     Mlt::Tractor tractor(service);
3029     Mlt::Producer trackProducer(tractor.track(track));
3030     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3031
3032     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3033     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3034     if (!clip) {
3035         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3036         return false;
3037     }
3038
3039     int duration = clip->get_playtime();
3040     bool doRefresh = true;
3041     // Check if clip is visible in monitor
3042     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3043     if (diff < 0 || diff > duration)
3044         doRefresh = false;
3045     int ct = 0;
3046
3047     Mlt::Filter *filter = clip->filter(ct);
3048     while (filter) {
3049         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3050             filter->set("disable", (int) disable);
3051         }
3052         ct++;
3053         filter = clip->filter(ct);
3054     }
3055
3056     delete clip;
3057     service.unlock();
3058
3059     if (doRefresh) refresh();
3060     return true;
3061 }
3062
3063 bool Render::mltEnableTrackEffects(int track, QList <int> effectIndexes, bool disable)
3064 {
3065     Mlt::Service service(m_mltProducer->parent().get_service());
3066     Mlt::Tractor tractor(service);
3067     Mlt::Producer trackProducer(tractor.track(track));
3068     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3069     Mlt::Service clipService(trackPlaylist.get_service());
3070     int ct = 0;
3071
3072     Mlt::Filter *filter = clipService.filter(ct);
3073     while (filter) {
3074         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3075             filter->set("disable", (int) disable);
3076         }
3077         ct++;
3078         filter = clipService.filter(ct);
3079     }
3080     service.unlock();
3081
3082     refresh();
3083     return true;
3084 }
3085
3086 void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
3087 {
3088     Mlt::Service service(m_mltProducer->parent().get_service());
3089     Mlt::Tractor tractor(service);
3090     Mlt::Producer trackProducer(tractor.track(track));
3091     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3092
3093     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3094     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3095     if (!clip) {
3096         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3097         return;
3098     }
3099
3100     Mlt::Service clipService(clip->get_service());
3101     int duration = clip->get_playtime();
3102     bool doRefresh = true;
3103     // Check if clip is visible in monitor
3104     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3105     if (diff < 0 || diff > duration) doRefresh = false;
3106     delete clip;
3107
3108     int ct = 0;
3109     Mlt::Filter *filter = clipService.filter(ct);
3110     while (filter) {
3111         int pos = filter->get_int("kdenlive_ix");
3112         if (pos == oldPos) {
3113             filter->set("kdenlive_ix", newPos);
3114         } else ct++;
3115         filter = clipService.filter(ct);
3116     }
3117     if (doRefresh) refresh();
3118 }
3119
3120 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
3121 {
3122     if (position < GenTime()) {
3123         mltMoveTrackEffect(track, oldPos, newPos);
3124         return;
3125     }
3126     Mlt::Service service(m_mltProducer->parent().get_service());
3127     Mlt::Tractor tractor(service);
3128     Mlt::Producer trackProducer(tractor.track(track));
3129     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3130
3131     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3132     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3133     if (!clip) {
3134         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3135         return;
3136     }
3137
3138     Mlt::Service clipService(clip->get_service());
3139     int duration = clip->get_playtime();
3140     bool doRefresh = true;
3141     // Check if clip is visible in monitor
3142     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3143     if (diff < 0 || diff > duration) doRefresh = false;
3144     delete clip;
3145
3146     int ct = 0;
3147     QList <Mlt::Filter *> filtersList;
3148     Mlt::Filter *filter = clipService.filter(ct);
3149     bool found = false;
3150     if (newPos > oldPos) {
3151         while (filter) {
3152             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3153                 filter->set("kdenlive_ix", newPos);
3154                 filtersList.append(filter);
3155                 clipService.detach(*filter);
3156                 filter = clipService.filter(ct);
3157                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3158                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3159                     ct++;
3160                     filter = clipService.filter(ct);
3161                 }
3162                 found = true;
3163             }
3164             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3165                 filtersList.append(filter);
3166                 clipService.detach(*filter);
3167             } else ct++;
3168             filter = clipService.filter(ct);
3169         }
3170     } else {
3171         while (filter) {
3172             if (filter->get_int("kdenlive_ix") == oldPos) {
3173                 filter->set("kdenlive_ix", newPos);
3174                 filtersList.append(filter);
3175                 clipService.detach(*filter);
3176             } else ct++;
3177             filter = clipService.filter(ct);
3178         }
3179
3180         ct = 0;
3181         filter = clipService.filter(ct);
3182         while (filter) {
3183             int pos = filter->get_int("kdenlive_ix");
3184             if (pos >= newPos) {
3185                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3186                 filtersList.append(filter);
3187                 clipService.detach(*filter);
3188             } else ct++;
3189             filter = clipService.filter(ct);
3190         }
3191     }
3192
3193     for (int i = 0; i < filtersList.count(); i++) {
3194         clipService.attach(*(filtersList.at(i)));
3195     }
3196
3197     if (doRefresh) refresh();
3198 }
3199
3200 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
3201 {
3202     Mlt::Service service(m_mltProducer->parent().get_service());
3203     Mlt::Tractor tractor(service);
3204     Mlt::Producer trackProducer(tractor.track(track));
3205     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3206     Mlt::Service clipService(trackPlaylist.get_service());
3207     int ct = 0;
3208     QList <Mlt::Filter *> filtersList;
3209     Mlt::Filter *filter = clipService.filter(ct);
3210     bool found = false;
3211     if (newPos > oldPos) {
3212         while (filter) {
3213             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3214                 filter->set("kdenlive_ix", newPos);
3215                 filtersList.append(filter);
3216                 clipService.detach(*filter);
3217                 filter = clipService.filter(ct);
3218                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3219                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3220                     ct++;
3221                     filter = clipService.filter(ct);
3222                 }
3223                 found = true;
3224             }
3225             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3226                 filtersList.append(filter);
3227                 clipService.detach(*filter);
3228             } else ct++;
3229             filter = clipService.filter(ct);
3230         }
3231     } else {
3232         while (filter) {
3233             if (filter->get_int("kdenlive_ix") == oldPos) {
3234                 filter->set("kdenlive_ix", newPos);
3235                 filtersList.append(filter);
3236                 clipService.detach(*filter);
3237             } else ct++;
3238             filter = clipService.filter(ct);
3239         }
3240
3241         ct = 0;
3242         filter = clipService.filter(ct);
3243         while (filter) {
3244             int pos = filter->get_int("kdenlive_ix");
3245             if (pos >= newPos) {
3246                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3247                 filtersList.append(filter);
3248                 clipService.detach(*filter);
3249             } else ct++;
3250             filter = clipService.filter(ct);
3251         }
3252     }
3253
3254     for (int i = 0; i < filtersList.count(); i++) {
3255         clipService.attach(*(filtersList.at(i)));
3256     }
3257     refresh();
3258 }
3259
3260 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
3261 {
3262     Mlt::Service service(m_mltProducer->parent().get_service());
3263     Mlt::Tractor tractor(service);
3264     Mlt::Producer trackProducer(tractor.track(info.track));
3265     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3266
3267     /* // Display playlist info
3268     kDebug()<<"////////////  BEFORE RESIZE";
3269     for (int i = 0; i < trackPlaylist.count(); i++) {
3270     int blankStart = trackPlaylist.clip_start(i);
3271     int blankDuration = trackPlaylist.clip_length(i) - 1;
3272     QString blk;
3273     if (trackPlaylist.is_blank(i)) blk = "(blank)";
3274     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
3275     }*/
3276
3277     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
3278         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3279         return false;
3280     }
3281     service.lock();
3282     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
3283     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
3284     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3285
3286     int previousStart = clip->get_in();
3287     int newDuration = (int) clipDuration.frames(m_fps) - 1;
3288     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
3289
3290     int currentOut = newDuration + previousStart;
3291     if (currentOut > clip->get_length()) {
3292         clip->parent().set("length", currentOut + 1);
3293         clip->parent().set("out", currentOut);
3294         clip->set("length", currentOut + 1);
3295     }
3296
3297     /*if (newDuration > clip->get_out()) {
3298         clip->parent().set_in_and_out(0, newDuration + 1);
3299         clip->set_in_and_out(0, newDuration + 1);
3300     }*/
3301     delete clip;
3302     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
3303     trackPlaylist.consolidate_blanks(0);
3304     // skip to next clip
3305     clipIndex++;
3306     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
3307     if (diff > 0) {
3308         // clip was made longer, trim next blank if there is one.
3309         if (clipIndex < trackPlaylist.count()) {
3310             // If this is not the last clip in playlist
3311             if (trackPlaylist.is_blank(clipIndex)) {
3312                 int blankStart = trackPlaylist.clip_start(clipIndex);
3313                 int blankDuration = trackPlaylist.clip_length(clipIndex);
3314                 if (diff > blankDuration) {
3315                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
3316                 }
3317                 if (diff - blankDuration == 0) {
3318                     trackPlaylist.remove(clipIndex);
3319                 } else trackPlaylist.remove_region(blankStart, diff);
3320             } else {
3321                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
3322             }
3323         }
3324     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
3325     trackPlaylist.consolidate_blanks(0);
3326     service.unlock();
3327
3328     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
3329     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3330         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
3331         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3332         ItemInfo transpinfo;
3333         transpinfo.startPos = info.startPos;
3334         transpinfo.endPos = info.startPos + clipDuration;
3335         transpinfo.track = info.track;
3336         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3337     }*/
3338     m_mltConsumer->set("refresh", 1);
3339     return true;
3340 }
3341
3342 void Render::mltChangeTrackState(int track, bool mute, bool blind)
3343 {
3344     Mlt::Service service(m_mltProducer->parent().get_service());
3345     Mlt::Tractor tractor(service);
3346     Mlt::Producer trackProducer(tractor.track(track));
3347
3348     // Make sure muting will not produce problems with our audio mixing transition,
3349     // because audio mixing is done between each track and the lowest one
3350     bool audioMixingBroken = false;
3351     if (mute && trackProducer.get_int("hide") < 2 ) {
3352             // We mute a track with sound
3353             if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3354             kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
3355     }
3356     else if (!mute && trackProducer.get_int("hide") > 1 ) {
3357             // We un-mute a previously muted track
3358             if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3359     }
3360
3361     if (mute) {
3362         if (blind) trackProducer.set("hide", 3);
3363         else trackProducer.set("hide", 2);
3364     } else if (blind) {
3365         trackProducer.set("hide", 1);
3366     } else {
3367         trackProducer.set("hide", 0);
3368     }
3369     if (audioMixingBroken) fixAudioMixing(tractor);
3370
3371     tractor.multitrack()->refresh();
3372     tractor.refresh();
3373     refresh();
3374 }
3375
3376 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3377 {
3378     for (int i = 1; i < tractor.count(); i++) {
3379         Mlt::Producer trackProducer(tractor.track(i));
3380         if (trackProducer.get_int("hide") < 2) return i;
3381     }
3382     return tractor.count() - 1;
3383 }
3384
3385 void Render::fixAudioMixing(Mlt::Tractor tractor)
3386 {
3387     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3388     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3389
3390     mlt_service serv = m_mltProducer->parent().get_service();
3391     Mlt::Field *field = tractor.field();
3392     mlt_service_lock(serv);
3393
3394     mlt_service nextservice = mlt_service_get_producer(serv);
3395     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3396     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3397     QString resource = mlt_properties_get(properties, "mlt_service");
3398
3399     mlt_service nextservicetodisconnect;
3400      // Delete all audio mixing transitions
3401     while (mlt_type == "transition") {
3402         if (resource == "mix") {
3403             nextservicetodisconnect = nextservice;
3404             nextservice = mlt_service_producer(nextservice);
3405             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3406         }
3407         else nextservice = mlt_service_producer(nextservice);
3408         if (nextservice == NULL) break;
3409         properties = MLT_SERVICE_PROPERTIES(nextservice);
3410         mlt_type = mlt_properties_get(properties, "mlt_type");
3411         resource = mlt_properties_get(properties, "mlt_service");
3412     }
3413
3414     // Re-add correct audio transitions
3415     for (int i = lowestTrack + 1; i < tractor.count(); i++) {
3416         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3417         transition->set("always_active", 1);
3418         transition->set("combine", 1);
3419         transition->set("internal_added", 237);
3420         field->plant_transition(*transition, lowestTrack, i);
3421     }
3422     mlt_service_unlock(serv);
3423 }
3424
3425 bool Render::mltResizeClipCrop(ItemInfo info, GenTime newCropStart)
3426 {
3427     Mlt::Service service(m_mltProducer->parent().get_service());
3428     int newCropFrame = (int) newCropStart.frames(m_fps);
3429     Mlt::Tractor tractor(service);
3430     Mlt::Producer trackProducer(tractor.track(info.track));
3431     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3432     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3433         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3434         return false;
3435     }
3436     service.lock();
3437     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3438     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3439     if (clip == NULL) {
3440         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3441         service.unlock();
3442         return false;
3443     }
3444     int previousStart = clip->get_in();
3445     int previousOut = clip->get_out();
3446     delete clip;
3447     if (previousStart == newCropFrame) {
3448         kDebug() << "////////  No ReSIZING Required";
3449         service.unlock();
3450         return true;
3451     }
3452     int frameOffset = newCropFrame - previousStart;
3453     trackPlaylist.resize_clip(clipIndex, newCropFrame, previousOut + frameOffset);
3454     service.unlock();
3455     m_mltConsumer->set("refresh", 1);
3456     return true;
3457 }
3458
3459 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3460 {
3461     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3462     Mlt::Service service(m_mltProducer->parent().get_service());
3463     int moveFrame = (int) diff.frames(m_fps);
3464     Mlt::Tractor tractor(service);
3465     Mlt::Producer trackProducer(tractor.track(info.track));
3466     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3467     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3468         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3469         return false;
3470     }
3471     service.lock();
3472     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3473     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3474     if (clip == NULL || clip->is_blank()) {
3475         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3476         service.unlock();
3477         return false;
3478     }
3479     int previousStart = clip->get_in();
3480     int previousOut = clip->get_out();
3481
3482     previousStart += moveFrame;
3483
3484     if (previousStart < 0) {
3485         // this is possible for images and color clips
3486         previousOut -= previousStart;
3487         previousStart = 0;
3488     }
3489
3490     int length = previousOut + 1;
3491     if (length > clip->get_length()) {
3492         clip->parent().set("length", length + 1);
3493         clip->parent().set("out", length);
3494         clip->set("length", length + 1);
3495     }
3496     delete clip;
3497
3498     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3499     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3500     if (moveFrame > 0) {
3501         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3502     } else {
3503         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3504         int blankIndex = clipIndex - 1;
3505         int blankLength = trackPlaylist.clip_length(blankIndex);
3506         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3507         if (! trackPlaylist.is_blank(blankIndex)) {
3508             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3509         }
3510         if (blankLength + moveFrame == 0)
3511             trackPlaylist.remove(blankIndex);
3512         else
3513             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3514     }
3515     trackPlaylist.consolidate_blanks(0);
3516     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3517         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3518         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3519         ItemInfo transpinfo;
3520         transpinfo.startPos = info.startPos + diff;
3521         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3522         transpinfo.track = info.track;
3523         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3524     }*/
3525     //m_mltConsumer->set("refresh", 1);
3526     service.unlock();
3527     m_mltConsumer->set("refresh", 1);
3528     return true;
3529 }
3530
3531 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3532 {
3533     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3534 }
3535
3536
3537 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3538 {
3539     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3540         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3541         return false;
3542     }
3543
3544     Mlt::Producer trackProducer(tractor->track(track));
3545     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3546     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3547     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3548     if (clipProducer == NULL || clipProducer->is_blank()) {
3549         kDebug() << "// ERROR UPDATING CLIP PROD";
3550         delete clipProducer;
3551         return false;
3552     }
3553     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3554     if (!clip || !clip->is_valid()) {
3555         if (clip) delete clip;
3556         delete clipProducer;
3557         return false;
3558     }
3559     // move all effects to the correct producer
3560     mltPasteEffects(clipProducer, clip);
3561     trackPlaylist.insert_at(pos, clip, 1);
3562     delete clip;
3563     delete clipProducer;
3564     return true;
3565 }
3566
3567 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3568 {
3569     Mlt::Service service(m_mltProducer->parent().get_service());
3570     if (service.type() != tractor_type) {
3571         kWarning() << "// TRACTOR PROBLEM";
3572         return false;
3573     }
3574
3575     Mlt::Tractor tractor(service);
3576     service.lock();
3577     Mlt::Producer trackProducer(tractor.track(startTrack));
3578     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3579     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3580     int clipDuration = trackPlaylist.clip_length(clipIndex);
3581     bool checkLength = false;
3582     if (endTrack == startTrack) {
3583         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3584         if (!overwrite) {
3585             bool success = true;
3586             if (!trackPlaylist.is_blank_at(moveEnd) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
3587                 success = false;
3588             }
3589             else {
3590                 // Check that the destination region is empty
3591                 trackPlaylist.consolidate_blanks(0);
3592                 int destinationIndex = trackPlaylist.get_clip_index_at(moveEnd);
3593                 if (destinationIndex < trackPlaylist.count() - 1) {
3594                     // We are not at the end of the track
3595                     int blankSize = trackPlaylist.blanks_from(destinationIndex, 1);
3596                     // Make sure we have enough place to insert clip
3597                     if (blankSize - clipDuration - (moveEnd - trackPlaylist.clip_start(destinationIndex)) < 0) success = false;
3598                 }
3599             }
3600             if (!success) {
3601                 if (clipProducer) {
3602                     trackPlaylist.insert_at(moveStart, clipProducer, 1);
3603                     delete clipProducer;
3604                 }
3605                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3606                 service.unlock();
3607                 return false;
3608             }
3609         }
3610         
3611         if (overwrite) {
3612             trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3613             int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
3614             trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
3615         }
3616         int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3617         if (newIndex == -1) {
3618             kDebug()<<"// CANNOT MOVE CLIP TO: "<<moveEnd;
3619             trackPlaylist.insert_at(moveStart, clipProducer, 1);
3620             delete clipProducer;
3621             service.unlock();
3622             return false;
3623         }
3624         trackPlaylist.consolidate_blanks(1);
3625         delete clipProducer;
3626         if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
3627     } else {
3628         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3629         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3630         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3631             // error, destination is not empty
3632             kDebug() << "Cannot move: Destination is not empty";
3633             service.unlock();
3634             return false;
3635         } else {
3636             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3637             if (!clipProducer || clipProducer->is_blank()) {
3638                 // error, destination is not empty
3639                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3640                 if (clipProducer) delete clipProducer;
3641                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3642                 service.unlock();
3643                 return false;
3644             }
3645             trackPlaylist.consolidate_blanks(0);
3646             destTrackPlaylist.consolidate_blanks(1);
3647             Mlt::Producer *clip;
3648             // check if we are moving a slowmotion producer
3649             QString serv = clipProducer->parent().get("mlt_service");
3650             QString currentid = clipProducer->parent().get("id");
3651             if (serv == "framebuffer") {
3652                 clip = clipProducer;
3653             } else {
3654                 if (prod == NULL) {
3655                     // Special case: prod is null when using placeholder clips.
3656                     // in that case, use the producer existing in playlist. Note that
3657                     // it will bypass the one producer per track logic and might cause
3658                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3659                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3660                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3661             }
3662
3663             // move all effects to the correct producer
3664             mltPasteEffects(clipProducer, clip);
3665
3666             if (overwrite) {
3667                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3668                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3669                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3670             }
3671
3672             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3673
3674             if (clip == clipProducer) {
3675                 delete clip;
3676                 clip = NULL;
3677             } else {
3678                 delete clip;
3679                 delete clipProducer;
3680             }
3681             destTrackPlaylist.consolidate_blanks(0);
3682             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3683                 kDebug() << "//////// moving clip transparency";
3684                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3685             }*/
3686             if (clipIndex > trackPlaylist.count()) checkLength = true;
3687             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3688         }
3689     }
3690     service.unlock();
3691     if (checkLength) mltCheckLength(&tractor);
3692     //askForRefresh();
3693     //m_mltConsumer->set("refresh", 1);
3694     return true;
3695 }
3696
3697
3698 QList <int> Render::checkTrackSequence(int track)
3699 {
3700     QList <int> list;
3701     Mlt::Service service(m_mltProducer->parent().get_service());
3702     if (service.type() != tractor_type) {
3703         kWarning() << "// TRACTOR PROBLEM";
3704         return list;
3705     }
3706     Mlt::Tractor tractor(service);
3707     service.lock();
3708     Mlt::Producer trackProducer(tractor.track(track));
3709     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3710     int clipNb = trackPlaylist.count();
3711     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3712     for (int i = 0; i < clipNb; i++) {
3713         Mlt::Producer *c = trackPlaylist.get_clip(i);
3714         int pos = trackPlaylist.clip_start(i);
3715         if (!list.contains(pos)) list.append(pos);
3716         pos += c->get_playtime();
3717         if (!list.contains(pos)) list.append(pos);
3718         delete c;
3719     }
3720     return list;
3721 }
3722
3723 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3724 {
3725     int new_in = (int)newIn.frames(m_fps);
3726     int new_out = (int)newOut.frames(m_fps) - 1;
3727     if (new_in >= new_out) return false;
3728     int old_in = (int)oldIn.frames(m_fps);
3729     int old_out = (int)oldOut.frames(m_fps) - 1;
3730
3731     Mlt::Service service(m_mltProducer->parent().get_service());
3732     Mlt::Tractor tractor(service);
3733     Mlt::Field *field = tractor.field();
3734
3735     bool doRefresh = true;
3736     // Check if clip is visible in monitor
3737     int diff = old_out - m_mltProducer->position();
3738     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3739     if (doRefresh) {
3740         diff = new_out - m_mltProducer->position();
3741         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3742     }
3743     service.lock();
3744
3745     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3746     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3747     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3748     QString resource = mlt_properties_get(properties, "mlt_service");
3749     int old_pos = (int)(old_in + old_out) / 2;
3750     bool found = false;
3751
3752     while (mlt_type == "transition") {
3753         Mlt::Transition transition((mlt_transition) nextservice);
3754         nextservice = mlt_service_producer(nextservice);
3755         int currentTrack = transition.get_b_track();
3756         int currentIn = (int) transition.get_in();
3757         int currentOut = (int) transition.get_out();
3758
3759         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3760             found = true;
3761             if (newTrack - startTrack != 0) {
3762                 Mlt::Properties trans_props(transition.get_properties());
3763                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3764                 Mlt::Properties new_trans_props(new_transition.get_properties());
3765                 new_trans_props.inherit(trans_props);
3766                 new_transition.set_in_and_out(new_in, new_out);
3767                 field->disconnect_service(transition);
3768                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3769                 //field->plant_transition(new_transition, newTransitionTrack, newTrack);
3770             } else transition.set_in_and_out(new_in, new_out);
3771             break;
3772         }
3773         if (nextservice == NULL) break;
3774         properties = MLT_SERVICE_PROPERTIES(nextservice);
3775         mlt_type = mlt_properties_get(properties, "mlt_type");
3776         resource = mlt_properties_get(properties, "mlt_service");
3777     }
3778     service.unlock();
3779     if (doRefresh) refresh();
3780     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3781     return found;
3782 }
3783
3784
3785 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3786 {
3787     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3788     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3789     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3790     QString resource = mlt_properties_get(properties, "mlt_service");
3791     QList <Mlt::Transition *> trList;
3792     mlt_properties insertproperties = tr.get_properties();
3793     QString insertresource = mlt_properties_get(insertproperties, "mlt_service");
3794     bool isMixTransition = insertresource == "mix";
3795
3796     while (mlt_type == "transition") {
3797         Mlt::Transition transition((mlt_transition) nextservice);
3798         nextservice = mlt_service_producer(nextservice);
3799         int aTrack = transition.get_a_track();
3800         int bTrack = transition.get_b_track();
3801         if ((isMixTransition || resource != "mix") && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3802             Mlt::Properties trans_props(transition.get_properties());
3803             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3804             Mlt::Properties new_trans_props(cp->get_properties());
3805             new_trans_props.inherit(trans_props);
3806             trList.append(cp);
3807             field->disconnect_service(transition);
3808         }
3809         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3810
3811         if (nextservice == NULL) break;
3812         properties = MLT_SERVICE_PROPERTIES(nextservice);
3813         mlt_type = mlt_properties_get(properties, "mlt_type");
3814         resource = mlt_properties_get(properties, "mlt_service");
3815     }
3816     field->plant_transition(tr, a_track, b_track);
3817
3818     // re-add upper transitions
3819     for (int i = trList.count() - 1; i >= 0; i--) {
3820         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3821         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3822     }
3823     qDeleteAll(trList);
3824 }
3825
3826 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3827 {
3828     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3829     else {
3830         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3831         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3832         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3833     }
3834
3835     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3836 }
3837
3838 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3839 {
3840     mlt_service serv = m_mltProducer->parent().get_service();
3841     mlt_service_lock(serv);
3842
3843     mlt_service nextservice = mlt_service_get_producer(serv);
3844     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3845     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3846     QString resource = mlt_properties_get(properties, "mlt_service");
3847     int in_pos = (int) in.frames(m_fps);
3848     int out_pos = (int) out.frames(m_fps) - 1;
3849
3850     while (mlt_type == "transition") {
3851         mlt_transition tr = (mlt_transition) nextservice;
3852         int currentTrack = mlt_transition_get_b_track(tr);
3853         int currentBTrack = mlt_transition_get_a_track(tr);
3854         int currentIn = (int) mlt_transition_get_in(tr);
3855         int currentOut = (int) mlt_transition_get_out(tr);
3856
3857         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
3858         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
3859             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
3860             QMap<QString, QString>::Iterator it;
3861             QString key;
3862             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
3863
3864             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
3865             if (currentId != xml.attribute("id")) {
3866                 // The transition ID is not the same, so reset all properties
3867                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
3868                 // Cleanup previous properties
3869                 QStringList permanentProps;
3870                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
3871                 permanentProps << "out" << "a_track" << "b_track";
3872                 for (int i = 0; i < mlt_properties_count(transproperties); i++) {
3873                     QString propName = mlt_properties_get_name(transproperties, i);
3874                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
3875                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
3876                     }
3877                 }
3878             }
3879
3880             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
3881             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
3882
3883             if (currentBTrack != a_track) {
3884                 mlt_properties_set_int(transproperties, "a_track", a_track);
3885             }
3886             for (it = map.begin(); it != map.end(); ++it) {
3887                 key = it.key();
3888                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
3889                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
3890                 //filter->set("kdenlive_id", id);
3891             }
3892             break;
3893         }
3894         nextservice = mlt_service_producer(nextservice);
3895         if (nextservice == NULL) break;
3896         properties = MLT_SERVICE_PROPERTIES(nextservice);
3897         mlt_type = mlt_properties_get(properties, "mlt_type");
3898         resource = mlt_properties_get(properties, "mlt_service");
3899     }
3900     mlt_service_unlock(serv);
3901     //askForRefresh();
3902     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3903 }
3904
3905 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
3906 {
3907     mlt_service serv = m_mltProducer->parent().get_service();
3908     mlt_service_lock(serv);
3909
3910     Mlt::Service service(serv);
3911     Mlt::Tractor tractor(service);
3912     Mlt::Field *field = tractor.field();
3913
3914     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3915
3916     mlt_service nextservice = mlt_service_get_producer(serv);
3917     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3918     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3919     QString resource = mlt_properties_get(properties, "mlt_service");
3920
3921     const int old_pos = (int)((in + out).frames(m_fps) / 2);
3922     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
3923
3924     while (mlt_type == "transition") {
3925         mlt_transition tr = (mlt_transition) nextservice;
3926         int currentTrack = mlt_transition_get_b_track(tr);
3927         int currentIn = (int) mlt_transition_get_in(tr);
3928         int currentOut = (int) mlt_transition_get_out(tr);
3929         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3930
3931         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3932             mlt_field_disconnect_service(field->get_field(), nextservice);
3933             break;
3934         }
3935         nextservice = mlt_service_producer(nextservice);
3936         if (nextservice == NULL) break;
3937         properties = MLT_SERVICE_PROPERTIES(nextservice);
3938         mlt_type = mlt_properties_get(properties, "mlt_type");
3939         resource = mlt_properties_get(properties, "mlt_service");
3940     }
3941     mlt_service_unlock(serv);
3942     //askForRefresh();
3943     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3944 }
3945
3946 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
3947 {
3948     QDomNodeList attribs = xml.elementsByTagName("parameter");
3949     QMap<QString, QString> map;
3950     for (int i = 0; i < attribs.count(); i++) {
3951         QDomElement e = attribs.item(i).toElement();
3952         QString name = e.attribute("name");
3953         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
3954         map[name] = e.attribute("default");
3955         if (!e.attribute("value").isEmpty()) {
3956             map[name] = e.attribute("value");
3957         }
3958         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
3959             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
3960             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
3961         }
3962
3963         if (e.attribute("namedesc").contains(';')) {
3964             QString format = e.attribute("format");
3965             QStringList separators = format.split("%d", QString::SkipEmptyParts);
3966             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
3967             QString neu;
3968             QTextStream txtNeu(&neu);
3969             if (values.size() > 0)
3970                 txtNeu << (int)values[0].toDouble();
3971             int i = 0;
3972             for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
3973                 txtNeu << separators[i];
3974                 txtNeu << (int)(values[i+1].toDouble());
3975             }
3976             if (i < separators.size())
3977                 txtNeu << separators[i];
3978             map[e.attribute("name")] = neu;
3979         }
3980
3981     }
3982     return map;
3983 }
3984
3985 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
3986 {
3987     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
3988     Mlt::Service service(m_mltProducer->parent().get_service());
3989     Mlt::Tractor tractor(service);
3990     Mlt::Field *field = tractor.field();
3991
3992     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
3993     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
3994     transition->set("transparency", id);
3995     transition->set("fill", 1);
3996     transition->set("internal_added", 237);
3997     field->plant_transition(*transition, transitiontrack, info.track);
3998     refresh();
3999 }
4000
4001 void Render::mltDeleteTransparency(int pos, int track, int id)
4002 {
4003     Mlt::Service service(m_mltProducer->parent().get_service());
4004     Mlt::Tractor tractor(service);
4005     Mlt::Field *field = tractor.field();
4006
4007     //if (do_refresh) m_mltConsumer->set("refresh", 0);
4008     mlt_service serv = m_mltProducer->parent().get_service();
4009
4010     mlt_service nextservice = mlt_service_get_producer(serv);
4011     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4012     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4013     QString resource = mlt_properties_get(properties, "mlt_service");
4014
4015     while (mlt_type == "transition") {
4016         mlt_transition tr = (mlt_transition) nextservice;
4017         int currentTrack = mlt_transition_get_b_track(tr);
4018         int currentIn = (int) mlt_transition_get_in(tr);
4019         int currentOut = (int) mlt_transition_get_out(tr);
4020         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4021         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
4022
4023         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
4024             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
4025             mlt_field_disconnect_service(field->get_field(), nextservice);
4026             break;
4027         }
4028         nextservice = mlt_service_producer(nextservice);
4029         if (nextservice == NULL) break;
4030         properties = MLT_SERVICE_PROPERTIES(nextservice);
4031         mlt_type = mlt_properties_get(properties, "mlt_type");
4032         resource = mlt_properties_get(properties, "mlt_service");
4033     }
4034     //if (do_refresh) m_mltConsumer->set("refresh", 1);
4035 }
4036
4037 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
4038 {
4039     Mlt::Service service(m_mltProducer->parent().get_service());
4040     Mlt::Tractor tractor(service);
4041
4042     service.lock();
4043     m_mltConsumer->set("refresh", 0);
4044
4045     mlt_service serv = m_mltProducer->parent().get_service();
4046     mlt_service nextservice = mlt_service_get_producer(serv);
4047     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4048     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4049     QString resource = mlt_properties_get(properties, "mlt_service");
4050     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
4051     while (mlt_type == "transition") {
4052         mlt_transition tr = (mlt_transition) nextservice;
4053         int currentTrack = mlt_transition_get_b_track(tr);
4054         int currentIn = (int) mlt_transition_get_in(tr);
4055         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
4056         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4057         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
4058         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
4059             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
4060             mlt_transition_set_in_and_out(tr, newStart, newEnd);
4061             break;
4062         }
4063         nextservice = mlt_service_producer(nextservice);
4064         if (nextservice == NULL) break;
4065         properties = MLT_SERVICE_PROPERTIES(nextservice);
4066         mlt_type = mlt_properties_get(properties, "mlt_type");
4067         resource = mlt_properties_get(properties, "mlt_service");
4068     }
4069     service.unlock();
4070     m_mltConsumer->set("refresh", 1);
4071
4072 }
4073
4074 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
4075 {
4076     Mlt::Service service(m_mltProducer->parent().get_service());
4077     Mlt::Tractor tractor(service);
4078
4079     service.lock();
4080     m_mltConsumer->set("refresh", 0);
4081
4082     mlt_service serv = m_mltProducer->parent().get_service();
4083     mlt_service nextservice = mlt_service_get_producer(serv);
4084     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4085     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4086     QString resource = mlt_properties_get(properties, "mlt_service");
4087
4088     while (mlt_type == "transition") {
4089         mlt_transition tr = (mlt_transition) nextservice;
4090         int currentTrack = mlt_transition_get_b_track(tr);
4091         int currentaTrack = mlt_transition_get_a_track(tr);
4092         int currentIn = (int) mlt_transition_get_in(tr);
4093         int currentOut = (int) mlt_transition_get_out(tr);
4094         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4095         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4096         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
4097         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
4098             kDebug() << "//////MOVING";
4099             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
4100             if (endTrack != startTrack) {
4101                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4102                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
4103                 mlt_properties_set_int(properties, "b_track", endTrack);
4104             }
4105             break;
4106         }
4107         nextservice = mlt_service_producer(nextservice);
4108         if (nextservice == NULL) break;
4109         properties = MLT_SERVICE_PROPERTIES(nextservice);
4110         mlt_type = mlt_properties_get(properties, "mlt_type");
4111         resource = mlt_properties_get(properties, "mlt_service");
4112     }
4113     service.unlock();
4114     m_mltConsumer->set("refresh", 1);
4115 }
4116
4117
4118 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
4119 {
4120     if (in >= out) return false;
4121     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
4122     Mlt::Service service(m_mltProducer->parent().get_service());
4123
4124     Mlt::Tractor tractor(service);
4125     Mlt::Field *field = tractor.field();
4126
4127     Mlt::Transition transition(*m_mltProfile, tag.toUtf8().constData());
4128     if (out != GenTime())
4129         transition.set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
4130
4131     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
4132     QMap<QString, QString>::Iterator it;
4133     QString key;
4134     if (xml.attribute("automatic") == "1") transition.set("automatic", 1);
4135     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
4136     if (xml.hasAttribute("id"))
4137         transition.set("kdenlive_id", xml.attribute("id").toUtf8().constData());
4138     if (xml.hasAttribute("force_track"))
4139         transition.set("force_track", xml.attribute("force_track").toInt());
4140
4141     for (it = args.begin(); it != args.end(); ++it) {
4142         key = it.key();
4143         if (!it.value().isEmpty())
4144             transition.set(key.toUtf8().constData(), it.value().toUtf8().constData());
4145         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
4146     }
4147     // attach transition
4148     service.lock();
4149     mltPlantTransition(field, transition, a_track, b_track);
4150     // field->plant_transition(*transition, a_track, b_track);
4151     service.unlock();
4152     if (do_refresh) refresh();
4153     return true;
4154 }
4155
4156 void Render::mltSavePlaylist()
4157 {
4158     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
4159     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
4160     fileConsumer.set("resource", "/tmp/playlist.mlt");
4161
4162     Mlt::Service service(m_mltProducer->get_service());
4163
4164     fileConsumer.connect(service);
4165     fileConsumer.start();
4166 }
4167
4168 const QList <Mlt::Producer *> Render::producersList()
4169 {
4170     QList <Mlt::Producer *> prods;
4171     if (m_mltProducer == NULL) return prods;
4172     Mlt::Service service(m_mltProducer->parent().get_service());
4173     if (service.type() != tractor_type) return prods;
4174     Mlt::Tractor tractor(service);
4175     QStringList ids;
4176
4177     int trackNb = tractor.count();
4178     for (int t = 1; t < trackNb; t++) {
4179         Mlt::Producer *tt = tractor.track(t);
4180         Mlt::Producer trackProducer(tt);
4181         delete tt;
4182         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4183         if (!trackPlaylist.is_valid()) continue;
4184         int clipNb = trackPlaylist.count();
4185         for (int i = 0; i < clipNb; i++) {
4186             Mlt::Producer *c = trackPlaylist.get_clip(i);
4187             if (c == NULL) continue;
4188             QString prodId = c->parent().get("id");
4189             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
4190                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4191                 if (nprod) {
4192                     ids.append(prodId);
4193                     prods.append(nprod);
4194                 }
4195             }
4196             delete c;
4197         }
4198     }
4199     return prods;
4200 }
4201
4202 void Render::fillSlowMotionProducers()
4203 {
4204     if (m_mltProducer == NULL) return;
4205     Mlt::Service service(m_mltProducer->parent().get_service());
4206     if (service.type() != tractor_type) return;
4207
4208     Mlt::Tractor tractor(service);
4209
4210     int trackNb = tractor.count();
4211     for (int t = 1; t < trackNb; t++) {
4212         Mlt::Producer *tt = tractor.track(t);
4213         Mlt::Producer trackProducer(tt);
4214         delete tt;
4215         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4216         if (!trackPlaylist.is_valid()) continue;
4217         int clipNb = trackPlaylist.count();
4218         for (int i = 0; i < clipNb; i++) {
4219             Mlt::Producer *c = trackPlaylist.get_clip(i);
4220             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4221             if (nprod) {
4222                 QString id = nprod->parent().get("id");
4223                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
4224                     // this is a slowmotion producer, add it to the list
4225                     QString url = QString::fromUtf8(nprod->get("resource"));
4226                     int strobe = nprod->get_int("strobe");
4227                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
4228                     if (!m_slowmotionProducers.contains(url)) {
4229                         m_slowmotionProducers.insert(url, nprod);
4230                     }
4231                 } else delete nprod;
4232             }
4233             delete c;
4234         }
4235     }
4236 }
4237
4238 QList <TransitionInfo> Render::mltInsertTrack(int ix, bool videoTrack)
4239 {
4240     Mlt::Service service(m_mltProducer->parent().get_service());
4241     if (service.type() != tractor_type) {
4242         kWarning() << "// TRACTOR PROBLEM";
4243         return QList <TransitionInfo> ();
4244     }
4245     blockSignals(true);
4246     service.lock();
4247     Mlt::Tractor tractor(service);
4248     QList <TransitionInfo> transitionInfos;
4249     Mlt::Playlist playlist;
4250     int ct = tractor.count();
4251     if (ix > ct) {
4252         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
4253         ix = ct;
4254     }
4255
4256     int pos = ix;
4257     if (pos < ct) {
4258         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
4259         tractor.set_track(playlist, pos);
4260         Mlt::Producer newProd(tractor.track(pos));
4261         if (!videoTrack) newProd.set("hide", 1);
4262         pos++;
4263         for (; pos <= ct; pos++) {
4264             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
4265             tractor.set_track(*prodToMove, pos);
4266             prodToMove = prodToMove2;
4267         }
4268     } else {
4269         tractor.set_track(playlist, ix);
4270         Mlt::Producer newProd(tractor.track(ix));
4271         if (!videoTrack) newProd.set("hide", 1);
4272     }
4273     checkMaxThreads();
4274
4275     // Move transitions
4276     mlt_service serv = m_mltProducer->parent().get_service();
4277     mlt_service nextservice = mlt_service_get_producer(serv);
4278     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4279     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4280     QString resource = mlt_properties_get(properties, "mlt_service");
4281     Mlt::Field *field = tractor.field();
4282     QList <Mlt::Transition *> trList;
4283
4284     while (mlt_type == "transition") {
4285         if (resource != "mix") {
4286             Mlt::Transition transition((mlt_transition) nextservice);
4287             nextservice = mlt_service_producer(nextservice);
4288             int currentbTrack = transition.get_b_track();
4289             int currentaTrack = transition.get_a_track();
4290             bool trackChanged = false;
4291             bool forceTransitionTrack = false;
4292             if (currentbTrack >= ix) {
4293                 if (currentbTrack == ix && currentaTrack < ix) forceTransitionTrack = true;
4294                 currentbTrack++;
4295                 trackChanged = true;
4296             }
4297             if (currentaTrack >= ix) {
4298                 currentaTrack++;
4299                 trackChanged = true;
4300             }
4301             kDebug()<<"// Newtrans: "<<currentaTrack<<"/"<<currentbTrack;
4302             
4303             // disconnect all transitions
4304             Mlt::Properties trans_props(transition.get_properties());
4305             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
4306             Mlt::Properties new_trans_props(cp->get_properties());
4307             new_trans_props.inherit(trans_props);
4308             
4309             if (trackChanged) {
4310                 // Transition track needs to be adjusted
4311                 cp->set("a_track", currentaTrack);
4312                 cp->set("b_track", currentbTrack);
4313                 // Check if transition track was changed and needs to be forced
4314                 if (forceTransitionTrack) cp->set("force_track", 1);
4315                 TransitionInfo trInfo;
4316                 trInfo.startPos = GenTime(transition.get_in(), m_fps);
4317                 trInfo.a_track = currentaTrack;
4318                 trInfo.b_track = currentbTrack;
4319                 trInfo.forceTrack = cp->get_int("force_track");
4320                 transitionInfos.append(trInfo);
4321             }
4322             trList.append(cp);
4323             field->disconnect_service(transition);
4324         }
4325         else nextservice = mlt_service_producer(nextservice);
4326         if (nextservice == NULL) break;
4327         properties = MLT_SERVICE_PROPERTIES(nextservice);
4328         mlt_type = mlt_properties_get(properties, "mlt_type");
4329         resource = mlt_properties_get(properties, "mlt_service");
4330     }
4331
4332     // Add audio mix transition to last track
4333     Mlt::Transition transition(*m_mltProfile, "mix");
4334     transition.set("a_track", 1);
4335     transition.set("b_track", ct);
4336     transition.set("always_active", 1);
4337     transition.set("internal_added", 237);
4338     transition.set("combine", 1);
4339     mltPlantTransition(field, transition, 1, ct);
4340     
4341     // re-add transitions
4342     for (int i = trList.count() - 1; i >= 0; i--) {
4343         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
4344     }
4345     qDeleteAll(trList);
4346     
4347     service.unlock();
4348     blockSignals(false);
4349     return transitionInfos;
4350 }
4351
4352
4353 void Render::mltDeleteTrack(int ix)
4354 {
4355     QDomDocument doc;
4356     doc.setContent(sceneList(), false);
4357     int tracksCount = doc.elementsByTagName("track").count() - 1;
4358     QDomNode track = doc.elementsByTagName("track").at(ix);
4359     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
4360     QDomNodeList transitions = doc.elementsByTagName("transition");
4361     for (int i = 0; i < transitions.count(); i++) {
4362         QDomElement e = transitions.at(i).toElement();
4363         QDomNodeList props = e.elementsByTagName("property");
4364         QMap <QString, QString> mappedProps;
4365         for (int j = 0; j < props.count(); j++) {
4366             QDomElement f = props.at(j).toElement();
4367             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
4368         }
4369         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
4370             tractor.removeChild(transitions.at(i));
4371             i--;
4372         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
4373             // Transition needs to be moved
4374             int a_track = mappedProps.value("a_track").toInt();
4375             int b_track = mappedProps.value("b_track").toInt();
4376             if (a_track > 0 && a_track >= ix) a_track --;
4377             if (b_track == ix) {
4378                 // transition was on the deleted track, so remove it
4379                 tractor.removeChild(transitions.at(i));
4380                 i--;
4381                 continue;
4382             }
4383             if (b_track > 0 && b_track > ix) b_track --;
4384             for (int j = 0; j < props.count(); j++) {
4385                 QDomElement f = props.at(j).toElement();
4386                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
4387                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
4388             }
4389
4390         }
4391     }
4392     tractor.removeChild(track);
4393     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
4394     setSceneList(doc.toString(), m_mltConsumer->position());
4395     emit refreshDocumentProducers(false, false);
4396 }
4397
4398
4399 void Render::updatePreviewSettings()
4400 {
4401     kDebug() << "////// RESTARTING CONSUMER";
4402     if (!m_mltConsumer || !m_mltProducer) return;
4403     if (m_mltProducer->get_playtime() == 0) return;
4404     QMutexLocker locker(&m_mutex);
4405     Mlt::Service service(m_mltProducer->parent().get_service());
4406     if (service.type() != tractor_type) return;
4407
4408     //m_mltConsumer->set("refresh", 0);
4409     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
4410     m_mltConsumer->purge();
4411     QString scene = sceneList();
4412     int pos = 0;
4413     if (m_mltProducer) {
4414         pos = m_mltProducer->position();
4415     }
4416
4417     setSceneList(scene, pos);
4418 }
4419
4420
4421 QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
4422 {
4423     // Update all frame positions to the new fps value
4424     //WARNING: there are probably some effects or other that hold a frame value
4425     // as parameter and will also need to be updated here!
4426     QDomDocument doc;
4427     doc.setContent(scene);
4428
4429     double factor = new_fps / current_fps;
4430     QDomNodeList producers = doc.elementsByTagName("producer");
4431     for (int i = 0; i < producers.count(); i++) {
4432         QDomElement prod = producers.at(i).toElement();
4433         prod.removeAttribute("in");
4434         prod.removeAttribute("out");
4435
4436         QDomNodeList props = prod.childNodes();
4437         for (int j = 0; j < props.count(); j++) {
4438             QDomElement param =  props.at(j).toElement();
4439             QString paramName = param.attribute("name");
4440             if (paramName.startsWith("meta.") || paramName == "length") {
4441                 prod.removeChild(props.at(j));
4442                 j--;
4443             }
4444         }
4445     }
4446
4447     QDomNodeList entries = doc.elementsByTagName("entry");
4448     for (int i = 0; i < entries.count(); i++) {
4449         QDomElement entry = entries.at(i).toElement();
4450         int in = entry.attribute("in").toInt();
4451         int out = entry.attribute("out").toInt();
4452         in = factor * in + 0.5;
4453         out = factor * out + 0.5;
4454         entry.setAttribute("in", in);
4455         entry.setAttribute("out", out);
4456     }
4457
4458     QDomNodeList blanks = doc.elementsByTagName("blank");
4459     for (int i = 0; i < blanks.count(); i++) {
4460         QDomElement blank = blanks.at(i).toElement();
4461         int length = blank.attribute("length").toInt();
4462         length = factor * length + 0.5;
4463         blank.setAttribute("length", QString::number(length));
4464     }
4465
4466     QDomNodeList filters = doc.elementsByTagName("filter");
4467     for (int i = 0; i < filters.count(); i++) {
4468         QDomElement filter = filters.at(i).toElement();
4469         int in = filter.attribute("in").toInt();
4470         int out = filter.attribute("out").toInt();
4471         in = factor * in + 0.5;
4472         out = factor * out + 0.5;
4473         filter.setAttribute("in", in);
4474         filter.setAttribute("out", out);
4475     }
4476
4477     QDomNodeList transitions = doc.elementsByTagName("transition");
4478     for (int i = 0; i < transitions.count(); i++) {
4479         QDomElement transition = transitions.at(i).toElement();
4480         int in = transition.attribute("in").toInt();
4481         int out = transition.attribute("out").toInt();
4482         in = factor * in + 0.5;
4483         out = factor * out + 0.5;
4484         transition.setAttribute("in", in);
4485         transition.setAttribute("out", out);
4486         QDomNodeList props = transition.childNodes();
4487         for (int j = 0; j < props.count(); j++) {
4488             QDomElement param =  props.at(j).toElement();
4489             QString paramName = param.attribute("name");
4490             if (paramName == "geometry") {
4491                 QString geom = param.firstChild().nodeValue();
4492                 QStringList keys = geom.split(';');
4493                 QStringList newKeys;
4494                 for (int k = 0; k < keys.size(); ++k) {
4495                     if (keys.at(k).contains('=')) {
4496                         int pos = keys.at(k).section('=', 0, 0).toInt();
4497                         pos = factor * pos + 0.5;
4498                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4499                     } else newKeys.append(keys.at(k));
4500                 }
4501                 param.firstChild().setNodeValue(newKeys.join(";"));
4502             }
4503         }
4504     }
4505     QDomElement root = doc.documentElement();
4506     if (!root.isNull()) {
4507         QDomElement tractor = root.firstChildElement("tractor");
4508         int out = tractor.attribute("out").toInt();
4509         out = factor * out + 0.5;
4510         tractor.setAttribute("out", out);
4511         emit durationChanged(out);
4512     }
4513
4514     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4515     return doc.toString();
4516 }
4517
4518
4519 void Render::sendFrameUpdate()
4520 {
4521     if (m_mltProducer) {
4522         Mlt::Frame * frame = m_mltProducer->get_frame();
4523         emitFrameUpdated(*frame);
4524         delete frame;
4525     }
4526 }
4527
4528 Mlt::Producer* Render::getProducer()
4529 {
4530     return m_mltProducer;
4531 }
4532
4533 const QString Render::activeClipId()
4534 {
4535     if (m_mltProducer) return m_mltProducer->get("id");
4536     return QString();
4537 }
4538
4539 //static 
4540 bool Render::getBlackMagicDeviceList(KComboBox *devicelist)
4541 {
4542     if (!KdenliveSettings::decklink_device_found()) return false;
4543     Mlt::Profile profile;
4544     Mlt::Producer bm(profile, "decklink");
4545     int found_devices = 0;
4546     if (bm.is_valid()) {
4547         bm.set("list_devices", 1);
4548         found_devices = bm.get_int("devices");
4549     }
4550     else KdenliveSettings::setDecklink_device_found(false);
4551     if (found_devices <= 0) {
4552         devicelist->setEnabled(false);
4553         return false;
4554     }
4555     for (int i = 0; i < found_devices; i++) {
4556         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4557         devicelist->addItem(bm.get(tmp));
4558         delete[] tmp;
4559     }
4560     return true;
4561 }
4562
4563 bool Render::getBlackMagicOutputDeviceList(KComboBox *devicelist)
4564 {
4565     if (!KdenliveSettings::decklink_device_found()) return false;
4566     Mlt::Profile profile;
4567     Mlt::Consumer bm(profile, "decklink");
4568     int found_devices = 0;
4569     if (bm.is_valid()) {
4570         bm.set("list_devices", 1);
4571         found_devices = bm.get_int("devices");
4572     }
4573     else KdenliveSettings::setDecklink_device_found(false);
4574     if (found_devices <= 0) {
4575         devicelist->setEnabled(false);
4576         return false;
4577     }
4578     for (int i = 0; i < found_devices; i++) {
4579         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4580         devicelist->addItem(bm.get(tmp));
4581         delete[] tmp;
4582     }
4583     return true;
4584 }
4585
4586 void Render::slotMultiStreamProducerFound(const QString path, QList<int> audio_list, QList<int> video_list, stringMap data)
4587
4588     if (KdenliveSettings::automultistreams()) {
4589         for (int i = 1; i < video_list.count(); i++) {
4590             int vindex = video_list.at(i);
4591             int aindex = 0;
4592             if (i <= audio_list.count() -1) {
4593                 aindex = audio_list.at(i);
4594             }
4595             data.insert("video_index", QString::number(vindex));
4596             data.insert("audio_index", QString::number(aindex));
4597             data.insert("bypassDuplicate", "1");
4598             emit addClip(KUrl(path), data);
4599         }
4600         return;
4601     }
4602     
4603     int width = 60.0 * m_mltProfile->dar();
4604     int swidth = 60.0 * m_mltProfile->width() / m_mltProfile->height();
4605     if (width % 2 == 1) width++;
4606
4607     KDialog dialog(qApp->activeWindow());
4608     dialog.setCaption("Multi Stream Clip");
4609     dialog.setButtons(KDialog::Ok | KDialog::Cancel);
4610     dialog.setButtonText(KDialog::Ok, i18n("Import selected clips"));
4611     QWidget *content = new QWidget(&dialog);
4612     dialog.setMainWidget(content);
4613     QVBoxLayout *vbox = new QVBoxLayout(content);
4614     QLabel *lab1 = new QLabel(i18n("Additional streams for clip\n %1", path), content);
4615     vbox->addWidget(lab1);
4616     QList <QGroupBox*> groupList;
4617     QList <QComboBox*> comboList;
4618     // We start loading the list at 1, video index 0 should already be loaded
4619     for (int j = 1; j < video_list.count(); j++) {
4620         Mlt::Producer multiprod(* m_mltProfile, path.toUtf8().constData());
4621         multiprod.set("video_index", video_list.at(j));
4622         QImage thumb = KThumb::getFrame(&multiprod, 0, swidth, width, 60);
4623         QGroupBox *streamFrame = new QGroupBox(i18n("Video stream %1", video_list.at(j)), content);
4624         streamFrame->setProperty("vindex", video_list.at(j));
4625         groupList << streamFrame;
4626         streamFrame->setCheckable(true);
4627         streamFrame->setChecked(true);
4628         QVBoxLayout *vh = new QVBoxLayout( streamFrame );
4629         QLabel *iconLabel = new QLabel(content);
4630         iconLabel->setPixmap(QPixmap::fromImage(thumb));
4631         vh->addWidget(iconLabel);
4632         if (audio_list.count() > 1) {
4633             QComboBox *cb = new QComboBox(content);
4634             for (int k = 0; k < audio_list.count(); k++) {
4635                 cb->addItem(i18n("Audio stream %1", audio_list.at(k)), audio_list.at(k));
4636             }
4637             comboList << cb;
4638             cb->setCurrentIndex(qMin(j, audio_list.count() - 1));
4639             vh->addWidget(cb);
4640         }
4641         vbox->addWidget(streamFrame);
4642     }
4643     if (dialog.exec() == QDialog::Accepted) {
4644         // import selected streams
4645         for (int i = 0; i < groupList.count(); i++) {
4646             if (groupList.at(i)->isChecked()) {
4647                 int vindex = groupList.at(i)->property("vindex").toInt();
4648                 int aindex = comboList.at(i)->itemData(comboList.at(i)->currentIndex()).toInt();
4649                 data.insert("video_index", QString::number(vindex));
4650                 data.insert("audio_index", QString::number(aindex));
4651                 data.insert("bypassDuplicate", "1");
4652                 emit addClip(KUrl(path), data);
4653             }
4654         }
4655     }
4656 }
4657
4658 #include "renderer.moc"
4659