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