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