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