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