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