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