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