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