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