]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Merge branch 'audioAlign' of git://anongit.kde.org/kdenlive into audioAlign
[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     if (!xmlConsumer.is_valid()) return QString();
1256     m_mltProducer->optimise();
1257     xmlConsumer.set("terminate_on_pause", 1);
1258     Mlt::Producer prod(m_mltProducer->get_producer());
1259     if (!prod.is_valid()) return QString();
1260     bool split = m_isSplitView;
1261     if (split) slotSplitView(false);
1262     xmlConsumer.connect(prod);
1263     xmlConsumer.run();
1264     playlist = QString::fromUtf8(xmlConsumer.get("kdenlive_playlist"));
1265     if (split) slotSplitView(true);
1266     return playlist;
1267 }
1268
1269 bool Render::saveSceneList(QString path, QDomElement kdenliveData)
1270 {
1271     QFile file(path);
1272     QDomDocument doc;
1273     doc.setContent(sceneList(), false);
1274     if (doc.isNull()) return false;
1275     QDomElement root = doc.documentElement();
1276     if (!kdenliveData.isNull() && !root.isNull()) {
1277         // add Kdenlive specific tags
1278         root.appendChild(doc.importNode(kdenliveData, true));
1279     }
1280     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1281         kWarning() << "//////  ERROR writing to file: " << path;
1282         return false;
1283     }
1284     file.write(doc.toString().toUtf8());
1285     if (file.error() != QFile::NoError) {
1286         file.close();
1287         return false;
1288     }
1289     file.close();
1290     return true;
1291 }
1292
1293 void Render::saveZone(KUrl url, QString desc, QPoint zone)
1294 {
1295     Mlt::Consumer xmlConsumer(*m_mltProfile, ("xml:" + url.path()).toUtf8().constData());
1296     m_mltProducer->optimise();
1297     xmlConsumer.set("terminate_on_pause", 1);
1298     if (m_name == "clip") {
1299         Mlt::Producer *prod = m_mltProducer->cut(zone.x(), zone.y());
1300         Mlt::Playlist list;
1301         list.insert_at(0, prod, 0);
1302         delete prod;
1303         list.set("title", desc.toUtf8().constData());
1304         xmlConsumer.connect(list);
1305
1306     } else {
1307         //TODO: not working yet, save zone from timeline
1308         Mlt::Producer *p1 = new Mlt::Producer(m_mltProducer->get_producer());
1309         /* Mlt::Service service(p1->parent().get_service());
1310          if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";*/
1311
1312         //Mlt::Producer *prod = p1->cut(zone.x(), zone.y());
1313         //prod->set("title", desc.toUtf8().constData());
1314         xmlConsumer.connect(*p1); //list);
1315     }
1316
1317     xmlConsumer.start();
1318 }
1319
1320 double Render::fps() const
1321 {
1322     return m_fps;
1323 }
1324
1325 int Render::volume() const
1326 {
1327     if (!m_mltConsumer || !m_mltProducer) return -1;
1328     return ((int) 100 * m_mltProducer->get_double("meta.volume"));
1329 }
1330
1331 void Render::slotSetVolume(int volume)
1332 {
1333     if (!m_mltConsumer || !m_mltProducer) return;
1334     m_mltProducer->set("meta.volume", (double)volume / 100.0);
1335     return;
1336     /*osdTimer->stop();
1337     m_mltConsumer->set("refresh", 0);
1338     // Attach filter for on screen display of timecode
1339     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1340     mlt_properties_set_double( properties, "meta.volume", volume );
1341     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
1342     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
1343
1344     if (!KdenliveSettings::osdtimecode()) {
1345     m_mltProducer->detach(*m_osdInfo);
1346     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
1347      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
1348     }*/
1349     refresh();
1350     //m_osdTimer->setSingleShot(2500);
1351 }
1352
1353 void Render::slotOsdTimeout()
1354 {
1355     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1356     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
1357     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
1358     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
1359     refresh();
1360 }
1361
1362 void Render::start()
1363 {
1364     m_refreshTimer.stop();
1365     QMutexLocker locker(&m_mutex);
1366     if (m_winid == -1) {
1367         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
1368         return;
1369     }
1370     if (!m_mltConsumer) return;
1371     if (m_mltConsumer->is_stopped()) {
1372         if (m_mltConsumer->start() == -1) {
1373             //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."));
1374             kDebug(QtWarningMsg) << "/ / / / CANNOT START MONITOR";
1375         } else {
1376             m_mltConsumer->purge();
1377             m_mltConsumer->set("refresh", 1);
1378         }
1379     }
1380 }
1381
1382 void Render::stop()
1383 {
1384     m_refreshTimer.stop();
1385     QMutexLocker locker(&m_mutex);
1386     if (m_mltProducer == NULL) return;
1387     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
1388         m_mltConsumer->stop();
1389         m_mltConsumer->purge();
1390     }
1391
1392     if (m_mltProducer) {
1393         if (m_isZoneMode) resetZoneMode();
1394         m_mltProducer->set_speed(0.0);
1395     }
1396 }
1397
1398 void Render::stop(const GenTime & startTime)
1399 {
1400     m_refreshTimer.stop();
1401     QMutexLocker locker(&m_mutex);
1402     if (m_mltProducer) {
1403         if (m_isZoneMode) resetZoneMode();
1404         m_mltProducer->set_speed(0.0);
1405         m_mltProducer->seek((int) startTime.frames(m_fps));
1406     }
1407     m_mltConsumer->purge();
1408 }
1409
1410 void Render::pause()
1411 {
1412     if (!m_mltProducer || !m_mltConsumer)
1413         return;
1414     if (m_mltProducer->get_speed() == 0.0) return;
1415     if (m_isZoneMode) resetZoneMode();
1416     m_mltConsumer->set("refresh", 0);
1417     m_mltProducer->set_speed(0.0);
1418     m_mltConsumer->purge();
1419 }
1420
1421 void Render::switchPlay(bool play)
1422 {
1423     QMutexLocker locker(&m_mutex);
1424     if (!m_mltProducer || !m_mltConsumer)
1425         return;
1426     if (m_isZoneMode) resetZoneMode();
1427     if (play && m_mltProducer->get_speed() == 0.0) {
1428         if (m_name == "clip" && m_mltConsumer->position() == m_mltProducer->get_out()) m_mltProducer->seek(0);
1429         if (m_mltConsumer->is_stopped()) {
1430             m_mltConsumer->start();
1431         }
1432         m_mltProducer->set_speed(1.0);
1433         m_mltConsumer->set("refresh", 1);
1434     } else if (!play) {
1435         m_mltProducer->set_speed(0.0);
1436         m_mltConsumer->set("refresh", 0);
1437         m_mltProducer->seek(m_mltConsumer->position());
1438         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1439         if (m_isZoneMode) resetZoneMode();
1440         
1441         //emitConsumerStopped();
1442         /*m_mltConsumer->set("refresh", 0);
1443         m_mltConsumer->stop();
1444         m_mltConsumer->purge();
1445         m_mltProducer->set_speed(0.0);
1446         //m_framePosition = m_mltProducer->position();
1447         m_mltProducer->seek(m_framePosition);
1448         emit rendererPosition(m_framePosition);*/
1449     }
1450 }
1451
1452 void Render::play(double speed)
1453 {
1454     if (!m_mltProducer)
1455         return;
1456     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1457     m_mltProducer->set_speed(speed);
1458     /*if (speed == 0.0) {
1459     m_mltProducer->seek((int) m_framePosition + 1);
1460         m_mltConsumer->purge();
1461     }*/
1462     refresh();
1463 }
1464
1465 void Render::play(const GenTime & startTime)
1466 {
1467     if (!m_mltProducer || !m_mltConsumer)
1468         return;
1469     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1470     m_mltProducer->set_speed(1.0);
1471     m_mltConsumer->set("refresh", 1);
1472 }
1473
1474 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime)
1475 {
1476     if (!m_mltProducer || !m_mltConsumer)
1477         return;
1478     //m_mltProducer->set("eof", "loop");
1479     m_isLoopMode = true;
1480     m_loopStart = startTime;
1481     playZone(startTime, stopTime);
1482 }
1483
1484 void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
1485 {
1486     if (!m_mltProducer || !m_mltConsumer)
1487         return;
1488     if (!m_isZoneMode) m_originalOut = m_mltProducer->get_playtime() - 1;
1489     m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
1490     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1491     m_mltProducer->set_speed(1.0);
1492     m_mltConsumer->set("refresh", 1);
1493     if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1494     m_isZoneMode = true;
1495 }
1496
1497 void Render::resetZoneMode()
1498 {
1499     if (!m_isZoneMode && !m_isLoopMode) return;
1500     m_mltProducer->set("out", m_originalOut);
1501     //m_mltProducer->set("eof", "pause");
1502     m_isZoneMode = false;
1503     m_isLoopMode = false;
1504 }
1505
1506 void Render::seekToFrame(int pos)
1507 {
1508     if (!m_mltProducer)
1509         return;
1510     resetZoneMode();
1511     m_mltProducer->seek(pos);
1512     if (m_mltProducer->get_speed() == 0) {
1513         refresh();
1514     }
1515 }
1516
1517 void Render::seekToFrameDiff(int diff)
1518 {
1519     if (!m_mltProducer)
1520         return;
1521     resetZoneMode();
1522     m_mltProducer->seek(m_mltProducer->position() + diff);
1523     refresh();
1524 }
1525
1526 void Render::doRefresh()
1527 {
1528     if (m_mltProducer && m_mltProducer->get_speed() == 0) m_refreshTimer.start();
1529 }
1530
1531 void Render::refresh()
1532 {
1533     QMutexLocker locker(&m_mutex);
1534     if (!m_mltProducer)
1535         return;
1536     if (m_mltConsumer) {
1537         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1538         m_mltConsumer->purge();
1539         m_mltConsumer->set("refresh", 1);
1540     }
1541 }
1542
1543 void Render::setDropFrames(bool show)
1544 {
1545     QMutexLocker locker(&m_mutex);
1546     if (m_mltConsumer) {
1547         int dropFrames = KdenliveSettings::mltthreads();
1548         if (show == false) dropFrames = -dropFrames;
1549         m_mltConsumer->stop();
1550         if (m_winid == 0)
1551             m_mltConsumer->set("real_time", dropFrames);
1552         else
1553             m_mltConsumer->set("play.real_time", dropFrames);
1554
1555         if (m_mltConsumer->start() == -1) {
1556             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1557         }
1558
1559     }
1560 }
1561
1562 double Render::playSpeed() const
1563 {
1564     if (m_mltProducer) return m_mltProducer->get_speed();
1565     return 0.0;
1566 }
1567
1568 GenTime Render::seekPosition() const
1569 {
1570     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1571     else return GenTime();
1572 }
1573
1574 int Render::seekFramePosition() const
1575 {
1576     //if (m_mltProducer) return (int) m_mltProducer->position();
1577     if (m_mltConsumer) return (int) m_mltConsumer->position();
1578     return 0;
1579 }
1580
1581 const QString & Render::rendererName() const
1582 {
1583     return m_name;
1584 }
1585
1586 void Render::emitFrameUpdated(Mlt::Frame& frame)
1587 {
1588     mlt_image_format format = mlt_image_rgb24;
1589     int width = 0;
1590     int height = 0;
1591     const uchar* image = frame.get_image(format, width, height);
1592     QImage qimage(width, height, QImage::Format_RGB888);
1593     memcpy(qimage.bits(), image, width * height * 3);
1594     emit frameUpdated(qimage);
1595 }
1596
1597 void Render::emitFrameNumber()
1598 {
1599     if (m_mltConsumer) emit rendererPosition((int) m_mltConsumer->position());
1600 }
1601
1602 void Render::emitConsumerStopped()
1603 {
1604     // This is used to know when the playing stopped
1605     if (m_mltProducer) {
1606         double pos = m_mltProducer->position();
1607         if (m_isLoopMode) play(m_loopStart);
1608         //else if (m_isZoneMode) resetZoneMode();
1609         emit rendererStopped((int) pos);
1610     }
1611 }
1612
1613 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1614 {
1615     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1616 }
1617
1618 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
1619 {
1620     if (!m_mltProducer) {
1621         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1622         return;
1623     }
1624
1625     //int height = 1080;//KdenliveSettings::defaultheight();
1626     //int width = 1940; //KdenliveSettings::displaywidth();
1627     //TODO: rewrite
1628     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1629     /*
1630        QPixmap pix(width, height);
1631        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1632        m_convert.set("forced", mlt_image_rgb24a);
1633        m_mltProducer->attach(m_convert);
1634        Mlt::Frame * frame = m_mltProducer->get_frame();
1635        m_mltProducer->detach(m_convert);
1636        if (frame) {
1637            pix = frameThumbnail(frame, width, height);
1638            delete frame;
1639        }*/
1640     pix.save(url.path(), "PNG");
1641     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1642 }
1643
1644
1645 void Render::showFrame(Mlt::Frame& frame)
1646 {
1647     emit rendererPosition((int) m_mltConsumer->position());
1648     mlt_image_format format = mlt_image_rgb24a;
1649     int width = 0;
1650     int height = 0;
1651     const uchar* image = frame.get_image(format, width, height);
1652     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1653     memcpy(qimage.scanLine(0), image, width * height * 4);
1654     emit showImageSignal(qimage);
1655     if (analyseAudio) showAudio(frame);
1656     if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
1657         emit frameUpdated(qimage.rgbSwapped());
1658     }
1659 }
1660
1661 void Render::showAudio(Mlt::Frame& frame)
1662 {
1663     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1664         return;
1665     }
1666     mlt_audio_format audio_format = mlt_audio_s16;
1667     int freq = 0;
1668     int num_channels = 0;
1669     int samples = 0;
1670     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1671
1672     if (!data) {
1673         return;
1674     }
1675
1676     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1677     // So the vector is of size samples*channels.
1678     QVector<int16_t> sampleVector(samples*num_channels);
1679     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1680
1681     if (samples > 0) {
1682         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1683     }
1684 }
1685
1686 /*
1687  * MLT playlist direct manipulation.
1688  */
1689
1690 void Render::mltCheckLength(Mlt::Tractor *tractor)
1691 {
1692     //kDebug()<<"checking track length: "<<track<<"..........";
1693
1694     int trackNb = tractor->count();
1695     int duration = 0;
1696     int trackDuration;
1697     if (trackNb == 1) {
1698         Mlt::Producer trackProducer(tractor->track(0));
1699         duration = trackProducer.get_playtime() - 1;
1700         m_mltProducer->set("out", duration);
1701         emit durationChanged(duration);
1702         return;
1703     }
1704     while (trackNb > 1) {
1705         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1706         trackDuration = trackProducer.get_playtime() - 1;
1707         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1708         if (trackDuration > duration) duration = trackDuration;
1709         trackNb--;
1710     }
1711
1712     Mlt::Producer blackTrackProducer(tractor->track(0));
1713
1714     if (blackTrackProducer.get_playtime() - 1 != duration) {
1715         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1716         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1717         if (blackclip && blackclip->is_blank()) {
1718             delete blackclip;
1719             blackclip = NULL;
1720         }
1721
1722         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
1723             if (blackclip) delete blackclip;
1724             blackTrackPlaylist.clear();
1725             m_blackClip->set("length", duration + 1);
1726             m_blackClip->set("out", duration);
1727             blackclip = m_blackClip->cut(0, duration);
1728             blackTrackPlaylist.insert_at(0, blackclip, 1);
1729         } else {
1730             if (duration > blackclip->parent().get_length()) {
1731                 blackclip->parent().set("length", duration + 1);
1732                 blackclip->parent().set("out", duration);
1733                 blackclip->set("length", duration + 1);
1734             }
1735             blackTrackPlaylist.resize_clip(0, 0, duration);
1736         }
1737
1738         delete blackclip;
1739         m_mltProducer->set("out", duration);
1740         emit durationChanged(duration);
1741     }
1742 }
1743
1744 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
1745 {
1746     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
1747     QLocale locale;
1748     // We want a slowmotion producer
1749     double speed = element.attribute("speed", "1.0").toDouble();
1750     int strobe = element.attribute("strobe", "1").toInt();
1751     QString url = QString::fromUtf8(prod->get("resource"));
1752     url.append('?' + locale.toString(speed));
1753     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
1754     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1755     if (!slowprod || slowprod->get_producer() == NULL) {
1756         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
1757         if (strobe > 1) slowprod->set("strobe", strobe);
1758         QString id = prod->parent().get("id");
1759         if (id.contains('_')) id = id.section('_', 0, 0);
1760         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
1761         if (strobe > 1) producerid.append(':' + QString::number(strobe));
1762         slowprod->set("id", producerid.toUtf8().constData());
1763         m_slowmotionProducers.insert(url, slowprod);
1764     }
1765     return slowprod;
1766 }
1767
1768 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
1769 {
1770     if (m_mltProducer == NULL) {
1771         kDebug() << "PLAYLIST NOT INITIALISED //////";
1772         return -1;
1773     }
1774     if (prod == NULL) {
1775         kDebug() << "Cannot insert clip without producer //////";
1776         return -1;
1777     }
1778     Mlt::Producer parentProd(m_mltProducer->parent());
1779     if (parentProd.get_producer() == NULL) {
1780         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1781         return -1;
1782     }
1783
1784     Mlt::Service service(parentProd.get_service());
1785     if (service.type() != tractor_type) {
1786         kWarning() << "// TRACTOR PROBLEM";
1787         return -1;
1788     }
1789     Mlt::Tractor tractor(service);
1790     if (info.track > tractor.count() - 1) {
1791         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
1792         return -1;
1793     }
1794     service.lock();
1795     Mlt::Producer trackProducer(tractor.track(info.track));
1796     int trackDuration = trackProducer.get_playtime() - 1;
1797     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1798     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
1799     prod = checkSlowMotionProducer(prod, element);
1800     if (prod == NULL || !prod->is_valid()) {
1801         service.unlock();
1802         return -1;
1803     }
1804
1805     int cutPos = (int) info.cropStart.frames(m_fps);
1806     if (cutPos < 0) cutPos = 0;
1807     int insertPos = (int) info.startPos.frames(m_fps);
1808     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
1809     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
1810     if (overwrite && (insertPos < trackDuration)) {
1811         // Replace zone with blanks
1812         //trackPlaylist.split_at(insertPos, true);
1813         trackPlaylist.remove_region(insertPos, cutDuration + 1);
1814         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1815         trackPlaylist.insert_blank(clipIndex, cutDuration);
1816     } else if (push) {
1817         trackPlaylist.split_at(insertPos, true);
1818         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1819         trackPlaylist.insert_blank(clipIndex, cutDuration);
1820     }
1821     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
1822     delete clip;
1823     /*if (QString(prod->get("transparency")).toInt() == 1)
1824         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
1825
1826     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
1827     service.unlock();
1828     /*tractor.multitrack()->refresh();
1829     tractor.refresh();*/
1830     return 0;
1831 }
1832
1833
1834 void Render::mltCutClip(int track, GenTime position)
1835 {
1836     Mlt::Service service(m_mltProducer->parent().get_service());
1837     if (service.type() != tractor_type) {
1838         kWarning() << "// TRACTOR PROBLEM";
1839         return;
1840     }
1841
1842     Mlt::Tractor tractor(service);
1843     Mlt::Producer trackProducer(tractor.track(track));
1844     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1845
1846
1847     /* // Display playlist info
1848     kDebug()<<"////////////  BEFORE";
1849     for (int i = 0; i < trackPlaylist.count(); i++) {
1850     int blankStart = trackPlaylist.clip_start(i);
1851     int blankDuration = trackPlaylist.clip_length(i) - 1;
1852     QString blk;
1853     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1854     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1855     }*/
1856
1857     int cutPos = (int) position.frames(m_fps);
1858
1859     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
1860     if (trackPlaylist.is_blank(clipIndex)) {
1861         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
1862         return;
1863     }
1864     service.lock();
1865     int clipStart = trackPlaylist.clip_start(clipIndex);
1866     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
1867     service.unlock();
1868
1869     // duplicate effects
1870     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
1871     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
1872
1873     if (original == NULL || clip == NULL) {
1874         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
1875     }
1876     Mlt::Service clipService(original->get_service());
1877     Mlt::Service dupService(clip->get_service());
1878     delete original;
1879     delete clip;
1880     int ct = 0;
1881     Mlt::Filter *filter = clipService.filter(ct);
1882     while (filter) {
1883         // Only duplicate Kdenlive filters, and skip the fade in effects
1884         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
1885             // looks like there is no easy way to duplicate a filter,
1886             // so we will create a new one and duplicate its properties
1887             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
1888             if (dup && dup->is_valid()) {
1889                 Mlt::Properties entries(filter->get_properties());
1890                 for (int i = 0; i < entries.count(); i++) {
1891                     dup->set(entries.get_name(i), entries.get(i));
1892                 }
1893                 dupService.attach(*dup);
1894             }
1895         }
1896         ct++;
1897         filter = clipService.filter(ct);
1898     }
1899
1900     /* // Display playlist info
1901     kDebug()<<"////////////  AFTER";
1902     for (int i = 0; i < trackPlaylist.count(); i++) {
1903     int blankStart = trackPlaylist.clip_start(i);
1904     int blankDuration = trackPlaylist.clip_length(i) - 1;
1905     QString blk;
1906     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1907     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1908     }*/
1909
1910 }
1911
1912 Mlt::Tractor *Render::lockService()
1913 {
1914     // we are going to replace some clips, purge consumer
1915     QMutexLocker locker(&m_mutex);
1916     if (!m_mltProducer) return NULL;
1917     if (m_mltConsumer) {
1918         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1919         m_mltConsumer->purge();
1920     }
1921     Mlt::Service service(m_mltProducer->parent().get_service());
1922     if (service.type() != tractor_type) {
1923         kWarning() << "// TRACTOR PROBLEM";
1924         return NULL;
1925     }
1926     service.lock();
1927     return new Mlt::Tractor(service);
1928     
1929 }
1930
1931 void Render::unlockService(Mlt::Tractor *tractor)
1932 {
1933     if (tractor) {
1934         delete tractor;
1935     }
1936     if (!m_mltProducer) return;
1937     Mlt::Service service(m_mltProducer->parent().get_service());
1938     if (service.type() != tractor_type) {
1939         kWarning() << "// TRACTOR PROBLEM";
1940         return;
1941     }
1942     service.unlock();
1943 }
1944
1945 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
1946 {
1947     // TODO: optimize
1948     if (prod == NULL || tractor == NULL) {
1949         kDebug() << "Cannot update clip with null producer //////";
1950         return false;
1951     }
1952
1953     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
1954     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1955     int startPos = info.startPos.frames(m_fps);
1956     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
1957     if (trackPlaylist.is_blank(clipIndex)) {
1958         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
1959         return false;
1960     }
1961     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
1962     // keep effects
1963     QList <Mlt::Filter *> filtersList;
1964     Mlt::Service sourceService(clip->get_service());
1965     int ct = 0;
1966     Mlt::Filter *filter = sourceService.filter(ct);
1967     while (filter) {
1968         if (filter->get_int("kdenlive_ix") != 0) {
1969             filtersList.append(filter);
1970         }
1971         ct++;
1972         filter = sourceService.filter(ct);
1973     }
1974     delete clip;
1975     clip = trackPlaylist.replace_with_blank(clipIndex);
1976     delete clip;
1977     prod = checkSlowMotionProducer(prod, element);
1978     if (prod == NULL || !prod->is_valid()) {
1979         return false;
1980     }
1981
1982     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
1983     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
1984     Mlt::Service destService(clip2->get_service());
1985     delete clip2;
1986
1987     if (!filtersList.isEmpty()) {
1988         for (int i = 0; i < filtersList.count(); i++)
1989             destService.attach(*(filtersList.at(i)));
1990     }
1991     return true;
1992 }
1993
1994
1995 bool Render::mltRemoveClip(int track, GenTime position)
1996 {
1997     Mlt::Service service(m_mltProducer->parent().get_service());
1998     if (service.type() != tractor_type) {
1999         kWarning() << "// TRACTOR PROBLEM";
2000         return false;
2001     }
2002     //service.lock();
2003     Mlt::Tractor tractor(service);
2004     Mlt::Producer trackProducer(tractor.track(track));
2005     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2006     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2007
2008     if (trackPlaylist.is_blank(clipIndex)) {
2009         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
2010         //service.unlock();
2011         return false;
2012     }
2013     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2014     if (clip) delete clip;
2015     trackPlaylist.consolidate_blanks(0);
2016
2017     /* // Display playlist info
2018     kDebug()<<"////  AFTER";
2019     for (int i = 0; i < trackPlaylist.count(); i++) {
2020     int blankStart = trackPlaylist.clip_start(i);
2021     int blankDuration = trackPlaylist.clip_length(i) - 1;
2022     QString blk;
2023     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2024     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2025     }*/
2026     //service.unlock();
2027     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
2028     return true;
2029 }
2030
2031 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
2032 {
2033     if (!m_mltProducer) {
2034         kDebug() << "PLAYLIST NOT INITIALISED //////";
2035         return 0;
2036     }
2037     Mlt::Producer parentProd(m_mltProducer->parent());
2038     if (parentProd.get_producer() == NULL) {
2039         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2040         return 0;
2041     }
2042
2043     Mlt::Service service(parentProd.get_service());
2044     Mlt::Tractor tractor(service);
2045     int insertPos = pos.frames(m_fps);
2046
2047     Mlt::Producer trackProducer(tractor.track(track));
2048     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2049     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2050     if (clipIndex == trackPlaylist.count()) {
2051         // We are after the end of the playlist
2052         return -1;
2053     }
2054     if (!trackPlaylist.is_blank(clipIndex)) return 0;
2055     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
2056     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
2057 }
2058
2059 int Render::mltTrackDuration(int track)
2060 {
2061     if (!m_mltProducer) {
2062         kDebug() << "PLAYLIST NOT INITIALISED //////";
2063         return -1;
2064     }
2065     Mlt::Producer parentProd(m_mltProducer->parent());
2066     if (parentProd.get_producer() == NULL) {
2067         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2068         return -1;
2069     }
2070
2071     Mlt::Service service(parentProd.get_service());
2072     Mlt::Tractor tractor(service);
2073
2074     Mlt::Producer trackProducer(tractor.track(track));
2075     return trackProducer.get_playtime() - 1;
2076 }
2077
2078 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
2079 {
2080     if (!m_mltProducer) {
2081         kDebug() << "PLAYLIST NOT INITIALISED //////";
2082         return;
2083     }
2084     Mlt::Producer parentProd(m_mltProducer->parent());
2085     if (parentProd.get_producer() == NULL) {
2086         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2087         return;
2088     }
2089     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
2090     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
2091
2092     Mlt::Service service(parentProd.get_service());
2093     Mlt::Tractor tractor(service);
2094     service.lock();
2095     int diff = duration.frames(m_fps);
2096     int offset = timeOffset.frames(m_fps);
2097     int insertPos;
2098
2099     if (track != -1) {
2100         // insert space in one track only
2101         Mlt::Producer trackProducer(tractor.track(track));
2102         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2103         insertPos = trackClipStartList.value(track);
2104         if (insertPos != -1) {
2105             insertPos += offset;
2106             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2107             if (diff > 0) {
2108                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2109             } else {
2110                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2111                 if (!trackPlaylist.is_blank(clipIndex)) {
2112                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2113                 }
2114                 int position = trackPlaylist.clip_start(clipIndex);
2115                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2116                 if (blankDuration + diff == 0) {
2117                     trackPlaylist.remove(clipIndex);
2118                 } else trackPlaylist.remove_region(position, -diff);
2119             }
2120             trackPlaylist.consolidate_blanks(0);
2121         }
2122         // now move transitions
2123         mlt_service serv = m_mltProducer->parent().get_service();
2124         mlt_service nextservice = mlt_service_get_producer(serv);
2125         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2126         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2127         QString resource = mlt_properties_get(properties, "mlt_service");
2128
2129         while (mlt_type == "transition") {
2130             mlt_transition tr = (mlt_transition) nextservice;
2131             int currentTrack = mlt_transition_get_b_track(tr);
2132             int currentIn = (int) mlt_transition_get_in(tr);
2133             int currentOut = (int) mlt_transition_get_out(tr);
2134             insertPos = trackTransitionStartList.value(track);
2135             if (insertPos != -1) {
2136                 insertPos += offset;
2137                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2138                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2139                 }
2140             }
2141             nextservice = mlt_service_producer(nextservice);
2142             if (nextservice == NULL) break;
2143             properties = MLT_SERVICE_PROPERTIES(nextservice);
2144             mlt_type = mlt_properties_get(properties, "mlt_type");
2145             resource = mlt_properties_get(properties, "mlt_service");
2146         }
2147     } else {
2148         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2149             Mlt::Producer trackProducer(tractor.track(trackNb));
2150             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2151
2152             //int clipNb = trackPlaylist.count();
2153             insertPos = trackClipStartList.value(trackNb);
2154             if (insertPos != -1) {
2155                 insertPos += offset;
2156
2157                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2158                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2159                         for (int i = 0; i < clipNb; i++) {
2160                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2161                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2162                      kDebug()<<"-------------";
2163                  }
2164                  kDebug()<<"END-------------";*/
2165
2166
2167                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2168                 if (diff > 0) {
2169                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2170                 } else {
2171                     if (!trackPlaylist.is_blank(clipIndex)) {
2172                         clipIndex --;
2173                     }
2174                     if (!trackPlaylist.is_blank(clipIndex)) {
2175                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2176                     }
2177                     int position = trackPlaylist.clip_start(clipIndex);
2178                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2179                     if (diff + blankDuration == 0) {
2180                         trackPlaylist.remove(clipIndex);
2181                     } else trackPlaylist.remove_region(position, - diff);
2182                 }
2183                 trackPlaylist.consolidate_blanks(0);
2184             }
2185         }
2186         // now move transitions
2187         mlt_service serv = m_mltProducer->parent().get_service();
2188         mlt_service nextservice = mlt_service_get_producer(serv);
2189         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2190         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2191         QString resource = mlt_properties_get(properties, "mlt_service");
2192
2193         while (mlt_type == "transition") {
2194             mlt_transition tr = (mlt_transition) nextservice;
2195             int currentIn = (int) mlt_transition_get_in(tr);
2196             int currentOut = (int) mlt_transition_get_out(tr);
2197             int currentTrack = mlt_transition_get_b_track(tr);
2198             insertPos = trackTransitionStartList.value(currentTrack);
2199             if (insertPos != -1) {
2200                 insertPos += offset;
2201                 if (currentOut > insertPos && resource != "mix") {
2202                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2203                 }
2204             }
2205             nextservice = mlt_service_producer(nextservice);
2206             if (nextservice == NULL) break;
2207             properties = MLT_SERVICE_PROPERTIES(nextservice);
2208             mlt_type = mlt_properties_get(properties, "mlt_type");
2209             resource = mlt_properties_get(properties, "mlt_service");
2210         }
2211     }
2212     service.unlock();
2213     mltCheckLength(&tractor);
2214     m_mltConsumer->set("refresh", 1);
2215 }
2216
2217
2218 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2219 {
2220     if (source == dest) return;
2221     Mlt::Service sourceService(source->get_service());
2222     Mlt::Service destService(dest->get_service());
2223
2224     // move all effects to the correct producer
2225     int ct = 0;
2226     Mlt::Filter *filter = sourceService.filter(ct);
2227     while (filter) {
2228         if (filter->get_int("kdenlive_ix") != 0) {
2229             sourceService.detach(*filter);
2230             destService.attach(*filter);
2231         } else ct++;
2232         filter = sourceService.filter(ct);
2233     }
2234 }
2235
2236 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2237 {
2238     int newLength = 0;
2239     Mlt::Service service(m_mltProducer->parent().get_service());
2240     if (service.type() != tractor_type) {
2241         kWarning() << "// TRACTOR PROBLEM";
2242         return -1;
2243     }
2244
2245     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2246     Mlt::Tractor tractor(service);
2247     Mlt::Producer trackProducer(tractor.track(info.track));
2248     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2249     int startPos = info.startPos.frames(m_fps);
2250     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2251     int clipLength = trackPlaylist.clip_length(clipIndex);
2252
2253     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2254     if (original == NULL) {
2255         return -1;
2256     }
2257     if (!original->is_valid() || original->is_blank()) {
2258         // invalid clip
2259         delete original;
2260         return -1;
2261     }
2262     Mlt::Producer clipparent = original->parent();
2263     if (!clipparent.is_valid() || clipparent.is_blank()) {
2264         // invalid clip
2265         delete original;
2266         return -1;
2267     }
2268
2269     QString serv = clipparent.get("mlt_service");
2270     QString id = clipparent.get("id");
2271     if (speed <= 0 && speed > -1) speed = 1.0;
2272     //kDebug() << "CLIP SERVICE: " << serv;
2273     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2274         service.lock();
2275         QString url = QString::fromUtf8(clipparent.get("resource"));
2276         url.append('?' + m_locale.toString(speed));
2277         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2278         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2279         if (!slowprod || slowprod->get_producer() == NULL) {
2280             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2281             if (strobe > 1) slowprod->set("strobe", strobe);
2282             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2283             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2284             slowprod->set("id", producerid.toUtf8().constData());
2285             // copy producer props
2286             double ar = original->parent().get_double("force_aspect_ratio");
2287             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2288             double fps = original->parent().get_double("force_fps");
2289             if (fps != 0.0) slowprod->set("force_fps", fps);
2290             int threads = original->parent().get_int("threads");
2291             if (threads != 0) slowprod->set("threads", threads);
2292             if (original->parent().get("force_progressive"))
2293                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2294             if (original->parent().get("force_tff"))
2295                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2296             int ix = original->parent().get_int("video_index");
2297             if (ix != 0) slowprod->set("video_index", ix);
2298             int colorspace = original->parent().get_int("force_colorspace");
2299             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2300             int full_luma = original->parent().get_int("set.force_full_luma");
2301             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2302             m_slowmotionProducers.insert(url, slowprod);
2303         }
2304         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2305         trackPlaylist.consolidate_blanks(0);
2306
2307         // Check that the blank space is long enough for our new duration
2308         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2309         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2310         Mlt::Producer *cut;
2311         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2312             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2313             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2314         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2315
2316         // move all effects to the correct producer
2317         mltPasteEffects(clip, cut);
2318         trackPlaylist.insert_at(startPos, cut, 1);
2319         delete cut;
2320         delete clip;
2321         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2322         newLength = trackPlaylist.clip_length(clipIndex);
2323         service.unlock();
2324     } else if (speed == 1.0 && strobe < 2) {
2325         service.lock();
2326
2327         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2328         trackPlaylist.consolidate_blanks(0);
2329
2330         // Check that the blank space is long enough for our new duration
2331         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2332         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2333
2334         Mlt::Producer *cut;
2335         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2336         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2337             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2338             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2339         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2340
2341         // move all effects to the correct producer
2342         mltPasteEffects(clip, cut);
2343
2344         trackPlaylist.insert_at(startPos, cut, 1);
2345         delete cut;
2346         delete clip;
2347         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2348         newLength = trackPlaylist.clip_length(clipIndex);
2349         service.unlock();
2350
2351     } else if (serv == "framebuffer") {
2352         service.lock();
2353         QString url = QString::fromUtf8(clipparent.get("resource"));
2354         url = url.section('?', 0, 0);
2355         url.append('?' + m_locale.toString(speed));
2356         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2357         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2358         if (!slowprod || slowprod->get_producer() == NULL) {
2359             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2360             slowprod->set("strobe", strobe);
2361             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2362             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2363             slowprod->set("id", producerid.toUtf8().constData());
2364             // copy producer props
2365             double ar = original->parent().get_double("force_aspect_ratio");
2366             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2367             double fps = original->parent().get_double("force_fps");
2368             if (fps != 0.0) slowprod->set("force_fps", fps);
2369             if (original->parent().get("force_progressive"))
2370                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2371             if (original->parent().get("force_tff"))
2372                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2373             int threads = original->parent().get_int("threads");
2374             if (threads != 0) slowprod->set("threads", threads);
2375             int ix = original->parent().get_int("video_index");
2376             if (ix != 0) slowprod->set("video_index", ix);
2377             int colorspace = original->parent().get_int("force_colorspace");
2378             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2379             int full_luma = original->parent().get_int("set.force_full_luma");
2380             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2381             m_slowmotionProducers.insert(url, slowprod);
2382         }
2383         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2384         trackPlaylist.consolidate_blanks(0);
2385
2386         GenTime duration = speedIndependantInfo.cropDuration / speed;
2387         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2388
2389         // Check that the blank space is long enough for our new duration
2390         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2391         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2392
2393         Mlt::Producer *cut;
2394         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2395             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2396             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2397         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2398
2399         // move all effects to the correct producer
2400         mltPasteEffects(clip, cut);
2401
2402         trackPlaylist.insert_at(startPos, cut, 1);
2403         delete cut;
2404         delete clip;
2405         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2406         newLength = trackPlaylist.clip_length(clipIndex);
2407
2408         service.unlock();
2409     }
2410     delete original;
2411     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2412     return newLength;
2413 }
2414
2415 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2416 {
2417     Mlt::Service service(m_mltProducer->parent().get_service());
2418     bool success = false;
2419     Mlt::Tractor tractor(service);
2420     Mlt::Producer trackProducer(tractor.track(track));
2421     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2422     Mlt::Service clipService(trackPlaylist.get_service());
2423
2424     service.lock();
2425     int ct = 0;
2426     Mlt::Filter *filter = clipService.filter(ct);
2427     while (filter) {
2428         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2429             if (clipService.detach(*filter) == 0) success = true;
2430         } else if (updateIndex) {
2431             // Adjust the other effects index
2432             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2433             ct++;
2434         } else ct++;
2435         filter = clipService.filter(ct);
2436     }
2437     service.unlock();
2438     refresh();
2439     return success;
2440 }
2441
2442 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2443 {
2444     if (position < GenTime()) {
2445         // Remove track effect
2446         return mltRemoveTrackEffect(track, index, updateIndex);
2447     }
2448     Mlt::Service service(m_mltProducer->parent().get_service());
2449     bool success = false;
2450     Mlt::Tractor tractor(service);
2451     Mlt::Producer trackProducer(tractor.track(track));
2452     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2453
2454     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2455     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2456     if (!clip) {
2457         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2458         return false;
2459     }
2460
2461     Mlt::Service clipService(clip->get_service());
2462     int duration = clip->get_playtime();
2463     if (doRefresh) {
2464         // Check if clip is visible in monitor
2465         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2466         if (diff < 0 || diff > duration) doRefresh = false;
2467     }
2468     delete clip;
2469
2470     service.lock();
2471     int ct = 0;
2472     Mlt::Filter *filter = clipService.filter(ct);
2473     while (filter) {
2474         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2475             if (clipService.detach(*filter) == 0) success = true;
2476             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2477         } else if (updateIndex) {
2478             // Adjust the other effects index
2479             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2480             ct++;
2481         } else ct++;
2482         filter = clipService.filter(ct);
2483     }
2484     service.unlock();
2485     if (doRefresh) refresh();
2486     return success;
2487 }
2488
2489 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2490 {
2491     Mlt::Service service(m_mltProducer->parent().get_service());
2492     Mlt::Tractor tractor(service);
2493     Mlt::Producer trackProducer(tractor.track(track));
2494     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2495     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2496     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2497 }
2498
2499
2500 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2501 {
2502
2503     Mlt::Service service(m_mltProducer->parent().get_service());
2504
2505     Mlt::Tractor tractor(service);
2506     Mlt::Producer trackProducer(tractor.track(track));
2507     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2508
2509     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2510     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2511     if (!clip) {
2512         return false;
2513     }
2514
2515     Mlt::Service clipService(clip->get_service());
2516     int duration = clip->get_playtime();
2517     if (doRefresh) {
2518         // Check if clip is visible in monitor
2519         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2520         if (diff < 0 || diff > duration) doRefresh = false;
2521     }
2522     delete clip;
2523     return mltAddEffect(clipService, params, duration, doRefresh);
2524 }
2525
2526 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2527 {
2528     bool updateIndex = false;
2529     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2530     const QString region =  params.paramValue("region");
2531     int ct = 0;
2532     service.lock();
2533
2534     Mlt::Filter *filter = service.filter(ct);
2535     while (filter) {
2536         if (filter->get_int("kdenlive_ix") == filter_ix) {
2537             // A filter at that position already existed, so we will increase all indexes later
2538             updateIndex = true;
2539             break;
2540         }
2541         ct++;
2542         filter = service.filter(ct);
2543     }
2544
2545     if (params.paramValue("id") == "speed") {
2546         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2547         ct = 0;
2548         filter = service.filter(ct);
2549         while (filter) {
2550             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2551                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2552             }
2553             ct++;
2554             filter = service.filter(ct);
2555         }
2556         service.unlock();
2557         if (doRefresh) refresh();
2558         return true;
2559     }
2560
2561
2562     // temporarily remove all effects after insert point
2563     QList <Mlt::Filter *> filtersList;
2564     ct = 0;
2565     filter = service.filter(ct);
2566     while (filter) {
2567         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2568             filtersList.append(filter);
2569             service.detach(*filter);
2570         } else ct++;
2571         filter = service.filter(ct);
2572     }
2573
2574     // create filter
2575     QString tag =  params.paramValue("tag");
2576     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2577     char *filterTag = qstrdup(tag.toUtf8().constData());
2578     char *filterId = qstrdup(params.paramValue("id").toUtf8().constData());
2579     QHash<QString, QString>::Iterator it;
2580     QString kfr = params.paramValue("keyframes");
2581
2582     if (!kfr.isEmpty()) {
2583         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2584         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2585         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2586         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2587         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2588         //double max = params.paramValue("max").toDouble();
2589         double min = params.paramValue("min").toDouble();
2590         double factor = params.paramValue("factor", "1").toDouble();
2591         double paramOffset = params.paramValue("offset", "0").toDouble();
2592         params.removeParam("starttag");
2593         params.removeParam("endtag");
2594         params.removeParam("keyframes");
2595         params.removeParam("min");
2596         params.removeParam("max");
2597         params.removeParam("factor");
2598         params.removeParam("offset");
2599         int offset = 0;
2600         // Special case, only one keyframe, means we want a constant value
2601         if (keyFrames.count() == 1) {
2602             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2603             if (filter && filter->is_valid()) {
2604                 filter->set("kdenlive_id", filterId);
2605                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2606                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2607                 for (int j = 0; j < params.count(); j++) {
2608                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2609                 }
2610                 filter->set("in", x1);
2611                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2612                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2613                 service.attach(*filter);
2614             }
2615         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2616                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2617                 if (filter && filter->is_valid()) {
2618                     filter->set("kdenlive_id", filterId);
2619                     int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2620                     double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2621                     int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2622                     double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2623                     if (x2 == -1) x2 = duration;
2624
2625                     for (int j = 0; j < params.count(); j++) {
2626                         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2627                     }
2628
2629                     filter->set("in", x1);
2630                     filter->set("out", x2);
2631                     //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2632                     filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2633                     filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2634                     service.attach(*filter);
2635                     offset = 1;
2636                 }
2637             }
2638         delete[] starttag;
2639         delete[] endtag;
2640     } else {
2641         Mlt::Filter *filter;
2642         QString prefix;
2643         if (!region.isEmpty()) {
2644             filter = new Mlt::Filter(*m_mltProfile, "region");
2645         } else filter = new Mlt::Filter(*m_mltProfile, filterTag);
2646         if (filter && filter->is_valid()) {
2647             filter->set("kdenlive_id", filterId);
2648             if (!region.isEmpty()) {
2649                 filter->set("resource", region.toUtf8().constData());
2650                 filter->set("kdenlive_ix", params.paramValue("kdenlive_ix").toUtf8().constData());
2651                 filter->set("filter0", filterTag);
2652                 prefix = "filter0.";
2653                 params.removeParam("id");
2654                 params.removeParam("region");
2655                 params.removeParam("kdenlive_ix");
2656             }
2657         } else {
2658             kDebug() << "filter is NULL";
2659             service.unlock();
2660             return false;
2661         }
2662         params.removeParam("kdenlive_id");
2663         if (params.hasParam("_sync_in_out")) {
2664             // This effect must sync in / out with parent clip
2665             params.removeParam("_sync_in_out");
2666             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2667         }
2668
2669         for (int j = 0; j < params.count(); j++) {
2670             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2671         }
2672
2673         if (tag == "sox") {
2674             QString effectArgs = params.paramValue("id").section('_', 1);
2675
2676             params.removeParam("id");
2677             params.removeParam("kdenlive_ix");
2678             params.removeParam("tag");
2679             params.removeParam("disable");
2680             params.removeParam("region");
2681
2682             for (int j = 0; j < params.count(); j++) {
2683                 effectArgs.append(' ' + params.at(j).value());
2684             }
2685             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2686             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2687         }
2688
2689         // attach filter to the clip
2690         service.attach(*filter);
2691     }
2692     delete[] filterId;
2693     delete[] filterTag;
2694
2695     // re-add following filters
2696     for (int i = 0; i < filtersList.count(); i++) {
2697         Mlt::Filter *filter = filtersList.at(i);
2698         if (updateIndex)
2699             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2700         service.attach(*filter);
2701     }
2702     service.unlock();
2703     if (doRefresh) refresh();
2704     return true;
2705 }
2706
2707 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
2708 {
2709     Mlt::Service service(m_mltProducer->parent().get_service());
2710     Mlt::Tractor tractor(service);
2711     Mlt::Producer trackProducer(tractor.track(track));
2712     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2713     Mlt::Service clipService(trackPlaylist.get_service());
2714     int ct = 0;
2715     QString index = params.paramValue("kdenlive_ix");
2716     QString tag =  params.paramValue("tag");
2717
2718     Mlt::Filter *filter = clipService.filter(ct);
2719     while (filter) {
2720         if (filter->get_int("kdenlive_ix") == index.toInt()) {
2721             break;
2722         }
2723         ct++;
2724         filter = clipService.filter(ct);
2725     }
2726
2727     if (!filter) {
2728         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2729         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2730
2731         bool success = false;//mltAddTrackEffect(track, params);
2732         return success;
2733     }
2734     QString prefix;
2735     QString ser = filter->get("mlt_service");
2736     if (ser == "region") prefix = "filter0.";
2737     service.lock();
2738     for (int j = 0; j < params.count(); j++) {
2739         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2740     }
2741     service.unlock();
2742
2743     refresh();
2744     return true;
2745
2746 }
2747
2748 bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList params)
2749 {
2750     int index = params.paramValue("kdenlive_ix").toInt();
2751     QString tag =  params.paramValue("tag");
2752
2753     if (!params.paramValue("keyframes").isEmpty() || /*it.key().startsWith("#") || */tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle" || params.hasParam("region")) {
2754         // This is a keyframe effect, to edit it, we remove it and re-add it.
2755         bool success = mltRemoveEffect(track, position, index, false);
2756 //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
2757         if (position < GenTime())
2758             success = mltAddTrackEffect(track, params);
2759         else
2760             success = mltAddEffect(track, position, params);
2761 //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
2762         return success;
2763     }
2764     if (position < GenTime()) {
2765         return mltEditTrackEffect(track, params);
2766     }
2767     // find filter
2768     Mlt::Service service(m_mltProducer->parent().get_service());
2769     Mlt::Tractor tractor(service);
2770     Mlt::Producer trackProducer(tractor.track(track));
2771     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2772
2773     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2774     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2775     if (!clip) {
2776         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2777         return false;
2778     }
2779
2780     int duration = clip->get_playtime();
2781     bool doRefresh = true;
2782     // Check if clip is visible in monitor
2783     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2784     if (diff < 0 || diff > duration)
2785         doRefresh = false;
2786     int ct = 0;
2787
2788     Mlt::Filter *filter = clip->filter(ct);
2789     while (filter) {
2790         if (filter->get_int("kdenlive_ix") == index) {
2791             break;
2792         }
2793         ct++;
2794         filter = clip->filter(ct);
2795     }
2796
2797     if (!filter) {
2798         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2799         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2800
2801         bool success = mltAddEffect(track, position, params);
2802         return success;
2803     }
2804     QString prefix;
2805     QString ser = filter->get("mlt_service");
2806     if (ser == "region") prefix = "filter0.";
2807     if (params.hasParam("_sync_in_out")) {
2808         // This effect must sync in / out with parent clip
2809         params.removeParam("_sync_in_out");
2810         filter->set_in_and_out(clip->get_in(), clip->get_out());
2811     }
2812     service.lock();
2813     for (int j = 0; j < params.count(); j++) {
2814         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2815     }   
2816
2817     delete clip;
2818     service.unlock();
2819
2820     if (doRefresh) refresh();
2821     return true;
2822 }
2823
2824 void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
2825 {
2826     Mlt::Service service(m_mltProducer->parent().get_service());
2827     Mlt::Tractor tractor(service);
2828     Mlt::Producer trackProducer(tractor.track(track));
2829     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2830
2831     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2832     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2833     if (!clip) {
2834         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2835         return;
2836     }
2837
2838     Mlt::Service clipService(clip->get_service());
2839     int duration = clip->get_playtime();
2840     bool doRefresh = true;
2841     // Check if clip is visible in monitor
2842     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2843     if (diff < 0 || diff > duration) doRefresh = false;
2844     delete clip;
2845
2846     int ct = 0;
2847     Mlt::Filter *filter = clipService.filter(ct);
2848     while (filter) {
2849         int pos = filter->get_int("kdenlive_ix");
2850         if (pos == oldPos) {
2851             filter->set("kdenlive_ix", newPos);
2852         } else ct++;
2853         filter = clipService.filter(ct);
2854     }
2855     if (doRefresh) refresh();
2856 }
2857
2858 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
2859 {
2860     if (position < GenTime()) {
2861         mltMoveTrackEffect(track, oldPos, newPos);
2862         return;
2863     }
2864     Mlt::Service service(m_mltProducer->parent().get_service());
2865     Mlt::Tractor tractor(service);
2866     Mlt::Producer trackProducer(tractor.track(track));
2867     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2868
2869     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2870     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2871     if (!clip) {
2872         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2873         return;
2874     }
2875
2876     Mlt::Service clipService(clip->get_service());
2877     int duration = clip->get_playtime();
2878     bool doRefresh = true;
2879     // Check if clip is visible in monitor
2880     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2881     if (diff < 0 || diff > duration) doRefresh = false;
2882     delete clip;
2883
2884     int ct = 0;
2885     QList <Mlt::Filter *> filtersList;
2886     Mlt::Filter *filter = clipService.filter(ct);
2887     bool found = false;
2888     if (newPos > oldPos) {
2889         while (filter) {
2890             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
2891                 filter->set("kdenlive_ix", newPos);
2892                 filtersList.append(filter);
2893                 clipService.detach(*filter);
2894                 filter = clipService.filter(ct);
2895                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
2896                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2897                     ct++;
2898                     filter = clipService.filter(ct);
2899                 }
2900                 found = true;
2901             }
2902             if (filter && filter->get_int("kdenlive_ix") > newPos) {
2903                 filtersList.append(filter);
2904                 clipService.detach(*filter);
2905             } else ct++;
2906             filter = clipService.filter(ct);
2907         }
2908     } else {
2909         while (filter) {
2910             if (filter->get_int("kdenlive_ix") == oldPos) {
2911                 filter->set("kdenlive_ix", newPos);
2912                 filtersList.append(filter);
2913                 clipService.detach(*filter);
2914             } else ct++;
2915             filter = clipService.filter(ct);
2916         }
2917
2918         ct = 0;
2919         filter = clipService.filter(ct);
2920         while (filter) {
2921             int pos = filter->get_int("kdenlive_ix");
2922             if (pos >= newPos) {
2923                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
2924                 filtersList.append(filter);
2925                 clipService.detach(*filter);
2926             } else ct++;
2927             filter = clipService.filter(ct);
2928         }
2929     }
2930
2931     for (int i = 0; i < filtersList.count(); i++) {
2932         clipService.attach(*(filtersList.at(i)));
2933     }
2934
2935     if (doRefresh) refresh();
2936 }
2937
2938 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
2939 {
2940     Mlt::Service service(m_mltProducer->parent().get_service());
2941     Mlt::Tractor tractor(service);
2942     Mlt::Producer trackProducer(tractor.track(track));
2943     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2944     Mlt::Service clipService(trackPlaylist.get_service());
2945     int ct = 0;
2946     QList <Mlt::Filter *> filtersList;
2947     Mlt::Filter *filter = clipService.filter(ct);
2948     bool found = false;
2949     if (newPos > oldPos) {
2950         while (filter) {
2951             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
2952                 filter->set("kdenlive_ix", newPos);
2953                 filtersList.append(filter);
2954                 clipService.detach(*filter);
2955                 filter = clipService.filter(ct);
2956                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
2957                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2958                     ct++;
2959                     filter = clipService.filter(ct);
2960                 }
2961                 found = true;
2962             }
2963             if (filter && filter->get_int("kdenlive_ix") > newPos) {
2964                 filtersList.append(filter);
2965                 clipService.detach(*filter);
2966             } else ct++;
2967             filter = clipService.filter(ct);
2968         }
2969     } else {
2970         while (filter) {
2971             if (filter->get_int("kdenlive_ix") == oldPos) {
2972                 filter->set("kdenlive_ix", newPos);
2973                 filtersList.append(filter);
2974                 clipService.detach(*filter);
2975             } else ct++;
2976             filter = clipService.filter(ct);
2977         }
2978
2979         ct = 0;
2980         filter = clipService.filter(ct);
2981         while (filter) {
2982             int pos = filter->get_int("kdenlive_ix");
2983             if (pos >= newPos) {
2984                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
2985                 filtersList.append(filter);
2986                 clipService.detach(*filter);
2987             } else ct++;
2988             filter = clipService.filter(ct);
2989         }
2990     }
2991
2992     for (int i = 0; i < filtersList.count(); i++) {
2993         clipService.attach(*(filtersList.at(i)));
2994     }
2995     refresh();
2996 }
2997
2998 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
2999 {
3000     Mlt::Service service(m_mltProducer->parent().get_service());
3001     Mlt::Tractor tractor(service);
3002     Mlt::Producer trackProducer(tractor.track(info.track));
3003     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3004
3005     /* // Display playlist info
3006     kDebug()<<"////////////  BEFORE RESIZE";
3007     for (int i = 0; i < trackPlaylist.count(); i++) {
3008     int blankStart = trackPlaylist.clip_start(i);
3009     int blankDuration = trackPlaylist.clip_length(i) - 1;
3010     QString blk;
3011     if (trackPlaylist.is_blank(i)) blk = "(blank)";
3012     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
3013     }*/
3014
3015     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
3016         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3017         return false;
3018     }
3019     service.lock();
3020     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
3021     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
3022     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3023
3024     int previousStart = clip->get_in();
3025     int newDuration = (int) clipDuration.frames(m_fps) - 1;
3026     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
3027
3028     int currentOut = newDuration + previousStart;
3029     if (currentOut > clip->get_length()) {
3030         clip->parent().set("length", currentOut + 1);
3031         clip->parent().set("out", currentOut);
3032         clip->set("length", currentOut + 1);
3033     }
3034
3035     /*if (newDuration > clip->get_out()) {
3036         clip->parent().set_in_and_out(0, newDuration + 1);
3037         clip->set_in_and_out(0, newDuration + 1);
3038     }*/
3039     delete clip;
3040     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
3041     trackPlaylist.consolidate_blanks(0);
3042     // skip to next clip
3043     clipIndex++;
3044     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
3045     if (diff > 0) {
3046         // clip was made longer, trim next blank if there is one.
3047         if (clipIndex < trackPlaylist.count()) {
3048             // If this is not the last clip in playlist
3049             if (trackPlaylist.is_blank(clipIndex)) {
3050                 int blankStart = trackPlaylist.clip_start(clipIndex);
3051                 int blankDuration = trackPlaylist.clip_length(clipIndex);
3052                 if (diff > blankDuration) {
3053                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
3054                 }
3055                 if (diff - blankDuration == 0) {
3056                     trackPlaylist.remove(clipIndex);
3057                 } else trackPlaylist.remove_region(blankStart, diff);
3058             } else {
3059                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
3060             }
3061         }
3062     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
3063     trackPlaylist.consolidate_blanks(0);
3064     service.unlock();
3065
3066     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
3067     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3068         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
3069         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3070         ItemInfo transpinfo;
3071         transpinfo.startPos = info.startPos;
3072         transpinfo.endPos = info.startPos + clipDuration;
3073         transpinfo.track = info.track;
3074         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3075     }*/
3076     m_mltConsumer->set("refresh", 1);
3077     return true;
3078 }
3079
3080 void Render::mltChangeTrackState(int track, bool mute, bool blind)
3081 {
3082     Mlt::Service service(m_mltProducer->parent().get_service());
3083     Mlt::Tractor tractor(service);
3084     Mlt::Producer trackProducer(tractor.track(track));
3085
3086     // Make sure muting will not produce problems with our audio mixing transition,
3087     // because audio mixing is done between each track and the lowest one
3088     bool audioMixingBroken = false;
3089     if (mute && trackProducer.get_int("hide") < 2 ) {
3090             // We mute a track with sound
3091             if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3092             kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
3093     }
3094     else if (!mute && trackProducer.get_int("hide") > 1 ) {
3095             // We un-mute a previously muted track
3096             if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3097     }
3098
3099     if (mute) {
3100         if (blind) trackProducer.set("hide", 3);
3101         else trackProducer.set("hide", 2);
3102     } else if (blind) {
3103         trackProducer.set("hide", 1);
3104     } else {
3105         trackProducer.set("hide", 0);
3106     }
3107     if (audioMixingBroken) fixAudioMixing(tractor);
3108     
3109     tractor.multitrack()->refresh();
3110     tractor.refresh();
3111     refresh();
3112 }
3113
3114 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3115 {
3116     for (int i = 1; i < tractor.count(); i++) {
3117         Mlt::Producer trackProducer(tractor.track(i));
3118         if (trackProducer.get_int("hide") < 2) return i;
3119     }
3120     return tractor.count() - 1;
3121 }
3122
3123 void Render::fixAudioMixing(Mlt::Tractor tractor)
3124 {
3125     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3126     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3127
3128     mlt_service serv = m_mltProducer->parent().get_service();
3129     Mlt::Field *field = tractor.field();
3130     mlt_service_lock(serv);
3131
3132     mlt_service nextservice = mlt_service_get_producer(serv);
3133     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3134     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3135     QString resource = mlt_properties_get(properties, "mlt_service");
3136
3137     mlt_service nextservicetodisconnect;
3138      // Delete all audio mixing transitions
3139     while (mlt_type == "transition") {
3140         if (resource == "mix") {
3141             nextservicetodisconnect = nextservice;
3142             nextservice = mlt_service_producer(nextservice);
3143             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3144         }
3145         else nextservice = mlt_service_producer(nextservice);
3146         if (nextservice == NULL) break;
3147         properties = MLT_SERVICE_PROPERTIES(nextservice);
3148         mlt_type = mlt_properties_get(properties, "mlt_type");
3149         resource = mlt_properties_get(properties, "mlt_service");
3150     }
3151
3152     // Re-add correct audio transitions
3153     for (int i = lowestTrack + 1; i < tractor.count(); i++) {
3154         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3155         transition->set("always_active", 1);
3156         transition->set("combine", 1);
3157         transition->set("internal_added", 237);
3158         field->plant_transition(*transition, lowestTrack, i);
3159     }
3160     mlt_service_unlock(serv);
3161 }
3162
3163 bool Render::mltResizeClipCrop(ItemInfo info, GenTime diff)
3164 {
3165     Mlt::Service service(m_mltProducer->parent().get_service());
3166     int frameOffset = (int) diff.frames(m_fps);
3167     Mlt::Tractor tractor(service);
3168     Mlt::Producer trackProducer(tractor.track(info.track));
3169     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3170     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3171         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3172         return false;
3173     }
3174     service.lock();
3175     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3176     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3177     if (clip == NULL) {
3178         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3179         service.unlock();
3180         return false;
3181     }
3182     int previousStart = clip->get_in();
3183     int previousOut = clip->get_out();
3184     delete clip;
3185     trackPlaylist.resize_clip(clipIndex, previousStart + frameOffset, previousOut + frameOffset);
3186     service.unlock();
3187     m_mltConsumer->set("refresh", 1);
3188     return true;
3189 }
3190
3191 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3192 {
3193     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3194     Mlt::Service service(m_mltProducer->parent().get_service());
3195     int moveFrame = (int) diff.frames(m_fps);
3196     Mlt::Tractor tractor(service);
3197     Mlt::Producer trackProducer(tractor.track(info.track));
3198     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3199     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3200         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3201         return false;
3202     }
3203     service.lock();
3204     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3205     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3206     if (clip == NULL || clip->is_blank()) {
3207         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3208         service.unlock();
3209         return false;
3210     }
3211     int previousStart = clip->get_in();
3212     int previousOut = clip->get_out();
3213
3214     previousStart += moveFrame;
3215
3216     if (previousStart < 0) {
3217         // this is possible for images and color clips
3218         previousOut -= previousStart;
3219         previousStart = 0;
3220     }
3221
3222     int length = previousOut + 1;
3223     if (length > clip->get_length()) {
3224         clip->parent().set("length", length + 1);
3225         clip->parent().set("out", length);
3226         clip->set("length", length + 1);
3227     }
3228     delete clip;
3229
3230     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3231     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3232     if (moveFrame > 0) {
3233         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3234     } else {
3235         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3236         int blankIndex = clipIndex - 1;
3237         int blankLength = trackPlaylist.clip_length(blankIndex);
3238         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3239         if (! trackPlaylist.is_blank(blankIndex)) {
3240             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3241         }
3242         if (blankLength + moveFrame == 0)
3243             trackPlaylist.remove(blankIndex);
3244         else
3245             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3246     }
3247     trackPlaylist.consolidate_blanks(0);
3248     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3249         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3250         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3251         ItemInfo transpinfo;
3252         transpinfo.startPos = info.startPos + diff;
3253         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3254         transpinfo.track = info.track;
3255         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3256     }*/
3257     //m_mltConsumer->set("refresh", 1);
3258     service.unlock();
3259     m_mltConsumer->set("refresh", 1);
3260     return true;
3261 }
3262
3263 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3264 {
3265     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3266 }
3267
3268
3269 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3270 {
3271     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3272         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3273         return false;
3274     }
3275
3276     Mlt::Producer trackProducer(tractor->track(track));
3277     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3278     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3279     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3280     if (clipProducer == NULL || clipProducer->is_blank()) {
3281         kDebug() << "// ERROR UPDATING CLIP PROD";
3282         delete clipProducer;
3283         return false;
3284     }
3285     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3286     if (!clip || !clip->is_valid()) {
3287         if (clip) delete clip;
3288         delete clipProducer;
3289         return false;
3290     }
3291     // move all effects to the correct producer
3292     mltPasteEffects(clipProducer, clip);
3293     trackPlaylist.insert_at(pos, clip, 1);
3294     delete clip;
3295     delete clipProducer;
3296     return true;
3297 }
3298
3299 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3300 {
3301     Mlt::Service service(m_mltProducer->parent().get_service());
3302     if (service.type() != tractor_type) {
3303         kWarning() << "// TRACTOR PROBLEM";
3304         return false;
3305     }
3306
3307     Mlt::Tractor tractor(service);
3308     service.lock();
3309     Mlt::Producer trackProducer(tractor.track(startTrack));
3310     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3311     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3312     //kDebug() << "//////  LOOKING FOR CLIP TO MOVE, INDEX: " << clipIndex;
3313     bool checkLength = false;
3314     if (endTrack == startTrack) {
3315         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3316         trackPlaylist.consolidate_blanks(0);
3317         if (!overwrite) {
3318             bool success = true;
3319             if (!trackPlaylist.is_blank_at(moveEnd) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) success = false;
3320             else {
3321                 // Check that the destination region is empty
3322                 int destinationIndex = trackPlaylist.get_clip_index_at(moveEnd);
3323                 if (destinationIndex < trackPlaylist.count() - 1) {
3324                     // We are not at the end of the track
3325                     int blankSize = trackPlaylist.blanks_from(destinationIndex, 0);
3326                     // Make sure we have enough place to insert clip
3327                     if (blankSize - clipProducer->get_length() - (moveEnd - trackPlaylist.clip_start(destinationIndex)) < 0) success = false;
3328                 }
3329             }
3330             if (!success) {
3331                 if (clipProducer) {
3332                     trackPlaylist.insert_at(moveStart, clipProducer, 1);
3333                     delete clipProducer;
3334                 }
3335                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3336                 service.unlock();
3337                 return false;
3338             }
3339         }
3340         
3341         if (overwrite) {
3342             trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3343             int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
3344             trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
3345         }
3346         int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3347         if (newIndex == -1) {
3348             kDebug()<<"// CANNOT MOVE CLIP TO: "<<moveEnd;
3349             trackPlaylist.insert_at(moveStart, clipProducer, 1);
3350             delete clipProducer;
3351             service.unlock();
3352             return false;
3353         }
3354         trackPlaylist.consolidate_blanks(1);
3355         delete clipProducer;
3356         if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
3357     } else {
3358         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3359         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3360         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3361             // error, destination is not empty
3362             kDebug() << "Cannot move: Destination is not empty";
3363             service.unlock();
3364             return false;
3365         } else {
3366             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3367             if (!clipProducer || clipProducer->is_blank()) {
3368                 // error, destination is not empty
3369                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3370                 if (clipProducer) delete clipProducer;
3371                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3372                 service.unlock();
3373                 return false;
3374             }
3375             trackPlaylist.consolidate_blanks(0);
3376             destTrackPlaylist.consolidate_blanks(1);
3377             Mlt::Producer *clip;
3378             // check if we are moving a slowmotion producer
3379             QString serv = clipProducer->parent().get("mlt_service");
3380             QString currentid = clipProducer->parent().get("id");
3381             if (serv == "framebuffer" || currentid.endsWith("_video")) {
3382                 clip = clipProducer;
3383             } else {
3384                 if (prod == NULL) {
3385                     // Special case: prod is null when using placeholder clips.
3386                     // in that case, use the producer existing in playlist. Note that
3387                     // it will bypass the one producer per track logic and might cause
3388                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3389                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3390                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3391             }
3392
3393             // move all effects to the correct producer
3394             mltPasteEffects(clipProducer, clip);
3395
3396             if (overwrite) {
3397                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3398                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3399                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3400             }
3401
3402             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3403
3404             if (clip == clipProducer) {
3405                 delete clip;
3406                 clip = NULL;
3407             } else {
3408                 delete clip;
3409                 delete clipProducer;
3410             }
3411             destTrackPlaylist.consolidate_blanks(0);
3412             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3413                 kDebug() << "//////// moving clip transparency";
3414                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3415             }*/
3416             if (clipIndex > trackPlaylist.count()) checkLength = true;
3417             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3418         }
3419     }
3420     service.unlock();
3421     if (checkLength) mltCheckLength(&tractor);
3422     //askForRefresh();
3423     //m_mltConsumer->set("refresh", 1);
3424     return true;
3425 }
3426
3427
3428 QList <int> Render::checkTrackSequence(int track)
3429 {
3430     QList <int> list;
3431     Mlt::Service service(m_mltProducer->parent().get_service());
3432     if (service.type() != tractor_type) {
3433         kWarning() << "// TRACTOR PROBLEM";
3434         return list;
3435     }
3436     Mlt::Tractor tractor(service);
3437     service.lock();
3438     Mlt::Producer trackProducer(tractor.track(track));
3439     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3440     int clipNb = trackPlaylist.count();
3441     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3442     for (int i = 0; i < clipNb; i++) {
3443         Mlt::Producer *c = trackPlaylist.get_clip(i);
3444         int pos = trackPlaylist.clip_start(i);
3445         if (!list.contains(pos)) list.append(pos);
3446         pos += c->get_playtime();
3447         if (!list.contains(pos)) list.append(pos);
3448         delete c;
3449     }
3450     return list;
3451 }
3452
3453 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3454 {
3455     int new_in = (int)newIn.frames(m_fps);
3456     int new_out = (int)newOut.frames(m_fps) - 1;
3457     if (new_in >= new_out) return false;
3458     int old_in = (int)oldIn.frames(m_fps);
3459     int old_out = (int)oldOut.frames(m_fps) - 1;
3460
3461     Mlt::Service service(m_mltProducer->parent().get_service());
3462     Mlt::Tractor tractor(service);
3463     Mlt::Field *field = tractor.field();
3464
3465     bool doRefresh = true;
3466     // Check if clip is visible in monitor
3467     int diff = old_out - m_mltProducer->position();
3468     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3469     if (doRefresh) {
3470         diff = new_out - m_mltProducer->position();
3471         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3472     }
3473     service.lock();
3474
3475     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3476     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3477     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3478     QString resource = mlt_properties_get(properties, "mlt_service");
3479     int old_pos = (int)(old_in + old_out) / 2;
3480     bool found = false;
3481
3482     while (mlt_type == "transition") {
3483         Mlt::Transition transition((mlt_transition) nextservice);
3484         int currentTrack = transition.get_b_track();
3485         int currentIn = (int) transition.get_in();
3486         int currentOut = (int) transition.get_out();
3487
3488         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3489             found = true;
3490             if (newTrack - startTrack != 0) {
3491                 Mlt::Properties trans_props(transition.get_properties());
3492                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3493                 Mlt::Properties new_trans_props(new_transition.get_properties());
3494                 new_trans_props.inherit(trans_props);
3495                 new_transition.set_in_and_out(new_in, new_out);
3496                 field->disconnect_service(transition);
3497                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3498                 //field->plant_transition(new_transition, newTransitionTrack, newTrack);
3499             } else transition.set_in_and_out(new_in, new_out);
3500             break;
3501         }
3502         nextservice = mlt_service_producer(nextservice);
3503         if (nextservice == NULL) break;
3504         properties = MLT_SERVICE_PROPERTIES(nextservice);
3505         mlt_type = mlt_properties_get(properties, "mlt_type");
3506         resource = mlt_properties_get(properties, "mlt_service");
3507     }
3508     service.unlock();
3509     if (doRefresh) refresh();
3510     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3511     return found;
3512 }
3513
3514
3515 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3516 {
3517     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3518     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3519     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3520     QString resource = mlt_properties_get(properties, "mlt_service");
3521     QList <Mlt::Transition *> trList;
3522
3523     while (mlt_type == "transition") {
3524         Mlt::Transition transition((mlt_transition) nextservice);
3525         int aTrack = transition.get_a_track();
3526         int bTrack = transition.get_b_track();
3527         if (resource != "mix" && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3528             Mlt::Properties trans_props(transition.get_properties());
3529             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3530             Mlt::Properties new_trans_props(cp->get_properties());
3531             new_trans_props.inherit(trans_props);
3532             trList.append(cp);
3533             field->disconnect_service(transition);
3534         }
3535         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3536
3537         nextservice = mlt_service_producer(nextservice);
3538         if (nextservice == NULL) break;
3539         properties = MLT_SERVICE_PROPERTIES(nextservice);
3540         mlt_type = mlt_properties_get(properties, "mlt_type");
3541         resource = mlt_properties_get(properties, "mlt_service");
3542     }
3543     field->plant_transition(tr, a_track, b_track);
3544
3545     // re-add upper transitions
3546     for (int i = trList.count() - 1; i >= 0; i--) {
3547         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3548         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3549     }
3550 }
3551
3552 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3553 {
3554     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3555     else {
3556         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3557         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3558         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3559     }
3560
3561     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3562 }
3563
3564 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3565 {
3566     mlt_service serv = m_mltProducer->parent().get_service();
3567     mlt_service_lock(serv);
3568
3569     mlt_service nextservice = mlt_service_get_producer(serv);
3570     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3571     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3572     QString resource = mlt_properties_get(properties, "mlt_service");
3573     int in_pos = (int) in.frames(m_fps);
3574     int out_pos = (int) out.frames(m_fps) - 1;
3575
3576     while (mlt_type == "transition") {
3577         mlt_transition tr = (mlt_transition) nextservice;
3578         int currentTrack = mlt_transition_get_b_track(tr);
3579         int currentBTrack = mlt_transition_get_a_track(tr);
3580         int currentIn = (int) mlt_transition_get_in(tr);
3581         int currentOut = (int) mlt_transition_get_out(tr);
3582
3583         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
3584         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
3585             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
3586             QMap<QString, QString>::Iterator it;
3587             QString key;
3588             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
3589
3590             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
3591             if (currentId != xml.attribute("id")) {
3592                 // The transition ID is not the same, so reset all properties
3593                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
3594                 // Cleanup previous properties
3595                 QStringList permanentProps;
3596                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
3597                 permanentProps << "out" << "a_track" << "b_track";
3598                 for (int i = 0; i < mlt_properties_count(transproperties); i++) {
3599                     QString propName = mlt_properties_get_name(transproperties, i);
3600                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
3601                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
3602                     }
3603                 }
3604             }
3605
3606             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
3607             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
3608
3609             if (currentBTrack != a_track) {
3610                 mlt_properties_set_int(transproperties, "a_track", a_track);
3611             }
3612             for (it = map.begin(); it != map.end(); ++it) {
3613                 key = it.key();
3614                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
3615                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
3616                 //filter->set("kdenlive_id", id);
3617             }
3618             break;
3619         }
3620         nextservice = mlt_service_producer(nextservice);
3621         if (nextservice == NULL) break;
3622         properties = MLT_SERVICE_PROPERTIES(nextservice);
3623         mlt_type = mlt_properties_get(properties, "mlt_type");
3624         resource = mlt_properties_get(properties, "mlt_service");
3625     }
3626     mlt_service_unlock(serv);
3627     //askForRefresh();
3628     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3629 }
3630
3631 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
3632 {
3633     mlt_service serv = m_mltProducer->parent().get_service();
3634     mlt_service_lock(serv);
3635
3636     Mlt::Service service(serv);
3637     Mlt::Tractor tractor(service);
3638     Mlt::Field *field = tractor.field();
3639
3640     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3641
3642     mlt_service nextservice = mlt_service_get_producer(serv);
3643     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3644     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3645     QString resource = mlt_properties_get(properties, "mlt_service");
3646
3647     const int old_pos = (int)((in + out).frames(m_fps) / 2);
3648     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
3649
3650     while (mlt_type == "transition") {
3651         mlt_transition tr = (mlt_transition) nextservice;
3652         int currentTrack = mlt_transition_get_b_track(tr);
3653         int currentIn = (int) mlt_transition_get_in(tr);
3654         int currentOut = (int) mlt_transition_get_out(tr);
3655         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3656
3657         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3658             mlt_field_disconnect_service(field->get_field(), nextservice);
3659             break;
3660         }
3661         nextservice = mlt_service_producer(nextservice);
3662         if (nextservice == NULL) break;
3663         properties = MLT_SERVICE_PROPERTIES(nextservice);
3664         mlt_type = mlt_properties_get(properties, "mlt_type");
3665         resource = mlt_properties_get(properties, "mlt_service");
3666     }
3667     mlt_service_unlock(serv);
3668     //askForRefresh();
3669     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3670 }
3671
3672 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
3673 {
3674     QDomNodeList attribs = xml.elementsByTagName("parameter");
3675     QMap<QString, QString> map;
3676     for (int i = 0; i < attribs.count(); i++) {
3677         QDomElement e = attribs.item(i).toElement();
3678         QString name = e.attribute("name");
3679         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
3680         map[name] = e.attribute("default");
3681         if (!e.attribute("value").isEmpty()) {
3682             map[name] = e.attribute("value");
3683         }
3684         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
3685             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
3686             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
3687         }
3688
3689         if (e.attribute("namedesc").contains(';')) {
3690             QString format = e.attribute("format");
3691             QStringList separators = format.split("%d", QString::SkipEmptyParts);
3692             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
3693             QString neu;
3694             QTextStream txtNeu(&neu);
3695             if (values.size() > 0)
3696                 txtNeu << (int)values[0].toDouble();
3697             int i = 0;
3698             for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
3699                 txtNeu << separators[i];
3700                 txtNeu << (int)(values[i+1].toDouble());
3701             }
3702             if (i < separators.size())
3703                 txtNeu << separators[i];
3704             map[e.attribute("name")] = neu;
3705         }
3706
3707     }
3708     return map;
3709 }
3710
3711 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
3712 {
3713     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
3714     Mlt::Service service(m_mltProducer->parent().get_service());
3715     Mlt::Tractor tractor(service);
3716     Mlt::Field *field = tractor.field();
3717
3718     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
3719     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
3720     transition->set("transparency", id);
3721     transition->set("fill", 1);
3722     transition->set("internal_added", 237);
3723     field->plant_transition(*transition, transitiontrack, info.track);
3724     refresh();
3725 }
3726
3727 void Render::mltDeleteTransparency(int pos, int track, int id)
3728 {
3729     Mlt::Service service(m_mltProducer->parent().get_service());
3730     Mlt::Tractor tractor(service);
3731     Mlt::Field *field = tractor.field();
3732
3733     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3734     mlt_service serv = m_mltProducer->parent().get_service();
3735
3736     mlt_service nextservice = mlt_service_get_producer(serv);
3737     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3738     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3739     QString resource = mlt_properties_get(properties, "mlt_service");
3740
3741     while (mlt_type == "transition") {
3742         mlt_transition tr = (mlt_transition) nextservice;
3743         int currentTrack = mlt_transition_get_b_track(tr);
3744         int currentIn = (int) mlt_transition_get_in(tr);
3745         int currentOut = (int) mlt_transition_get_out(tr);
3746         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3747         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3748
3749         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
3750             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
3751             mlt_field_disconnect_service(field->get_field(), nextservice);
3752             break;
3753         }
3754         nextservice = mlt_service_producer(nextservice);
3755         if (nextservice == NULL) break;
3756         properties = MLT_SERVICE_PROPERTIES(nextservice);
3757         mlt_type = mlt_properties_get(properties, "mlt_type");
3758         resource = mlt_properties_get(properties, "mlt_service");
3759     }
3760     //if (do_refresh) m_mltConsumer->set("refresh", 1);
3761 }
3762
3763 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
3764 {
3765     Mlt::Service service(m_mltProducer->parent().get_service());
3766     Mlt::Tractor tractor(service);
3767
3768     service.lock();
3769     m_mltConsumer->set("refresh", 0);
3770
3771     mlt_service serv = m_mltProducer->parent().get_service();
3772     mlt_service nextservice = mlt_service_get_producer(serv);
3773     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3774     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3775     QString resource = mlt_properties_get(properties, "mlt_service");
3776     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
3777     while (mlt_type == "transition") {
3778         mlt_transition tr = (mlt_transition) nextservice;
3779         int currentTrack = mlt_transition_get_b_track(tr);
3780         int currentIn = (int) mlt_transition_get_in(tr);
3781         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
3782         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3783         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
3784         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
3785             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
3786             mlt_transition_set_in_and_out(tr, newStart, newEnd);
3787             break;
3788         }
3789         nextservice = mlt_service_producer(nextservice);
3790         if (nextservice == NULL) break;
3791         properties = MLT_SERVICE_PROPERTIES(nextservice);
3792         mlt_type = mlt_properties_get(properties, "mlt_type");
3793         resource = mlt_properties_get(properties, "mlt_service");
3794     }
3795     service.unlock();
3796     m_mltConsumer->set("refresh", 1);
3797
3798 }
3799
3800 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
3801 {
3802     Mlt::Service service(m_mltProducer->parent().get_service());
3803     Mlt::Tractor tractor(service);
3804
3805     service.lock();
3806     m_mltConsumer->set("refresh", 0);
3807
3808     mlt_service serv = m_mltProducer->parent().get_service();
3809     mlt_service nextservice = mlt_service_get_producer(serv);
3810     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3811     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3812     QString resource = mlt_properties_get(properties, "mlt_service");
3813
3814     while (mlt_type == "transition") {
3815         mlt_transition tr = (mlt_transition) nextservice;
3816         int currentTrack = mlt_transition_get_b_track(tr);
3817         int currentaTrack = mlt_transition_get_a_track(tr);
3818         int currentIn = (int) mlt_transition_get_in(tr);
3819         int currentOut = (int) mlt_transition_get_out(tr);
3820         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
3821         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3822         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
3823         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
3824             kDebug() << "//////MOVING";
3825             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
3826             if (endTrack != startTrack) {
3827                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
3828                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
3829                 mlt_properties_set_int(properties, "b_track", endTrack);
3830             }
3831             break;
3832         }
3833         nextservice = mlt_service_producer(nextservice);
3834         if (nextservice == NULL) break;
3835         properties = MLT_SERVICE_PROPERTIES(nextservice);
3836         mlt_type = mlt_properties_get(properties, "mlt_type");
3837         resource = mlt_properties_get(properties, "mlt_service");
3838     }
3839     service.unlock();
3840     m_mltConsumer->set("refresh", 1);
3841 }
3842
3843
3844 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
3845 {
3846     if (in >= out) return false;
3847     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
3848     Mlt::Service service(m_mltProducer->parent().get_service());
3849
3850     Mlt::Tractor tractor(service);
3851     Mlt::Field *field = tractor.field();
3852
3853     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, tag.toUtf8().constData());
3854     if (out != GenTime())
3855         transition->set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
3856
3857     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
3858     QMap<QString, QString>::Iterator it;
3859     QString key;
3860     if (xml.attribute("automatic") == "1") transition->set("automatic", 1);
3861     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
3862     if (xml.hasAttribute("id"))
3863         transition->set("kdenlive_id", xml.attribute("id").toUtf8().constData());
3864     if (xml.hasAttribute("force_track"))
3865         transition->set("force_track", xml.attribute("force_track").toInt());
3866
3867     for (it = args.begin(); it != args.end(); ++it) {
3868         key = it.key();
3869         if (!it.value().isEmpty())
3870             transition->set(key.toUtf8().constData(), it.value().toUtf8().constData());
3871         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
3872     }
3873     // attach transition
3874     service.lock();
3875     mltPlantTransition(field, *transition, a_track, b_track);
3876     // field->plant_transition(*transition, a_track, b_track);
3877     service.unlock();
3878     if (do_refresh) refresh();
3879     return true;
3880 }
3881
3882 void Render::mltSavePlaylist()
3883 {
3884     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
3885     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
3886     fileConsumer.set("resource", "/tmp/playlist.mlt");
3887
3888     Mlt::Service service(m_mltProducer->get_service());
3889
3890     fileConsumer.connect(service);
3891     fileConsumer.start();
3892 }
3893
3894 const QList <Mlt::Producer *> Render::producersList()
3895 {
3896     QList <Mlt::Producer *> prods;
3897     if (m_mltProducer == NULL) return prods;
3898     Mlt::Service service(m_mltProducer->parent().get_service());
3899     if (service.type() != tractor_type) return prods;
3900     Mlt::Tractor tractor(service);
3901     QStringList ids;
3902
3903     int trackNb = tractor.count();
3904     for (int t = 1; t < trackNb; t++) {
3905         Mlt::Producer *tt = tractor.track(t);
3906         Mlt::Producer trackProducer(tt);
3907         delete tt;
3908         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3909         int clipNb = trackPlaylist.count();
3910         for (int i = 0; i < clipNb; i++) {
3911             Mlt::Producer *c = trackPlaylist.get_clip(i);
3912             if (c == NULL) continue;
3913             QString prodId = c->parent().get("id");
3914             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
3915                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
3916                 if (nprod) {
3917                     ids.append(prodId);
3918                     prods.append(nprod);
3919                 }
3920             }
3921             delete c;
3922         }
3923     }
3924     return prods;
3925 }
3926
3927 void Render::fillSlowMotionProducers()
3928 {
3929     if (m_mltProducer == NULL) return;
3930     Mlt::Service service(m_mltProducer->parent().get_service());
3931     if (service.type() != tractor_type) return;
3932
3933     Mlt::Tractor tractor(service);
3934
3935     int trackNb = tractor.count();
3936     for (int t = 1; t < trackNb; t++) {
3937         Mlt::Producer *tt = tractor.track(t);
3938         Mlt::Producer trackProducer(tt);
3939         delete tt;
3940         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3941         int clipNb = trackPlaylist.count();
3942         for (int i = 0; i < clipNb; i++) {
3943             Mlt::Producer *c = trackPlaylist.get_clip(i);
3944             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
3945             if (nprod) {
3946                 QString id = nprod->parent().get("id");
3947                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
3948                     // this is a slowmotion producer, add it to the list
3949                     QString url = QString::fromUtf8(nprod->get("resource"));
3950                     int strobe = nprod->get_int("strobe");
3951                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
3952                     if (!m_slowmotionProducers.contains(url)) {
3953                         m_slowmotionProducers.insert(url, nprod);
3954                     }
3955                 } else delete nprod;
3956             }
3957             delete c;
3958         }
3959     }
3960 }
3961
3962 void Render::mltInsertTrack(int ix, bool videoTrack)
3963 {
3964     blockSignals(true);
3965
3966     Mlt::Service service(m_mltProducer->parent().get_service());
3967     service.lock();
3968     if (service.type() != tractor_type) {
3969         kWarning() << "// TRACTOR PROBLEM";
3970         return;
3971     }
3972
3973     Mlt::Tractor tractor(service);
3974
3975     Mlt::Playlist playlist;
3976     int ct = tractor.count();
3977     if (ix > ct) {
3978         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
3979         ix = ct;
3980     }
3981
3982     int pos = ix;
3983     if (pos < ct) {
3984         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
3985         tractor.set_track(playlist, pos);
3986         Mlt::Producer newProd(tractor.track(pos));
3987         if (!videoTrack) newProd.set("hide", 1);
3988         pos++;
3989         for (; pos <= ct; pos++) {
3990             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
3991             tractor.set_track(*prodToMove, pos);
3992             prodToMove = prodToMove2;
3993         }
3994     } else {
3995         tractor.set_track(playlist, ix);
3996         Mlt::Producer newProd(tractor.track(ix));
3997         if (!videoTrack) newProd.set("hide", 1);
3998     }
3999     checkMaxThreads();
4000
4001     // Move transitions
4002     mlt_service serv = m_mltProducer->parent().get_service();
4003     mlt_service nextservice = mlt_service_get_producer(serv);
4004     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4005     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4006     QString resource = mlt_properties_get(properties, "mlt_service");
4007
4008     while (mlt_type == "transition") {
4009         if (resource != "mix") {
4010             mlt_transition tr = (mlt_transition) nextservice;
4011             int currentTrack = mlt_transition_get_b_track(tr);
4012             int currentaTrack = mlt_transition_get_a_track(tr);
4013             mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4014
4015             if (currentTrack >= ix) {
4016                 mlt_properties_set_int(properties, "b_track", currentTrack + 1);
4017                 mlt_properties_set_int(properties, "a_track", currentaTrack + 1);
4018             }
4019         }
4020         nextservice = mlt_service_producer(nextservice);
4021         if (nextservice == NULL) break;
4022         properties = MLT_SERVICE_PROPERTIES(nextservice);
4023         mlt_type = mlt_properties_get(properties, "mlt_type");
4024         resource = mlt_properties_get(properties, "mlt_service");
4025     }
4026
4027     // Add audio mix transition to last track
4028     Mlt::Field *field = tractor.field();
4029     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
4030     transition->set("a_track", 1);
4031     transition->set("b_track", ct);
4032     transition->set("always_active", 1);
4033     transition->set("internal_added", 237);
4034     transition->set("combine", 1);
4035     field->plant_transition(*transition, 1, ct);
4036     //mlt_service_unlock(m_mltConsumer->get_service());
4037     service.unlock();
4038     //tractor.multitrack()->refresh();
4039     //tractor.refresh();
4040     blockSignals(false);
4041 }
4042
4043
4044 void Render::mltDeleteTrack(int ix)
4045 {
4046     QDomDocument doc;
4047     doc.setContent(sceneList(), false);
4048     int tracksCount = doc.elementsByTagName("track").count() - 1;
4049     QDomNode track = doc.elementsByTagName("track").at(ix);
4050     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
4051     QDomNodeList transitions = doc.elementsByTagName("transition");
4052     for (int i = 0; i < transitions.count(); i++) {
4053         QDomElement e = transitions.at(i).toElement();
4054         QDomNodeList props = e.elementsByTagName("property");
4055         QMap <QString, QString> mappedProps;
4056         for (int j = 0; j < props.count(); j++) {
4057             QDomElement f = props.at(j).toElement();
4058             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
4059         }
4060         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
4061             tractor.removeChild(transitions.at(i));
4062             i--;
4063         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
4064             // Transition needs to be moved
4065             int a_track = mappedProps.value("a_track").toInt();
4066             int b_track = mappedProps.value("b_track").toInt();
4067             if (a_track > 0 && a_track >= ix) a_track --;
4068             if (b_track == ix) {
4069                 // transition was on the deleted track, so remove it
4070                 tractor.removeChild(transitions.at(i));
4071                 i--;
4072                 continue;
4073             }
4074             if (b_track > 0 && b_track > ix) b_track --;
4075             for (int j = 0; j < props.count(); j++) {
4076                 QDomElement f = props.at(j).toElement();
4077                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
4078                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
4079             }
4080
4081         }
4082     }
4083     tractor.removeChild(track);
4084     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
4085     setSceneList(doc.toString(), m_mltConsumer->position());
4086     emit refreshDocumentProducers(false, false);
4087 }
4088
4089
4090 void Render::updatePreviewSettings()
4091 {
4092     kDebug() << "////// RESTARTING CONSUMER";
4093     if (!m_mltConsumer || !m_mltProducer) return;
4094     if (m_mltProducer->get_playtime() == 0) return;
4095     QMutexLocker locker(&m_mutex);
4096     Mlt::Service service(m_mltProducer->parent().get_service());
4097     if (service.type() != tractor_type) return;
4098
4099     //m_mltConsumer->set("refresh", 0);
4100     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
4101     m_mltConsumer->purge();
4102     QString scene = sceneList();
4103     int pos = 0;
4104     if (m_mltProducer) {
4105         pos = m_mltProducer->position();
4106     }
4107
4108     setSceneList(scene, pos);
4109 }
4110
4111
4112 QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
4113 {
4114     // Update all frame positions to the new fps value
4115     //WARNING: there are probably some effects or other that hold a frame value
4116     // as parameter and will also need to be updated here!
4117     QDomDocument doc;
4118     doc.setContent(scene);
4119
4120     double factor = new_fps / current_fps;
4121     QDomNodeList producers = doc.elementsByTagName("producer");
4122     for (int i = 0; i < producers.count(); i++) {
4123         QDomElement prod = producers.at(i).toElement();
4124         prod.removeAttribute("in");
4125         prod.removeAttribute("out");
4126
4127         QDomNodeList props = prod.childNodes();
4128         for (int j = 0; j < props.count(); j++) {
4129             QDomElement param =  props.at(j).toElement();
4130             QString paramName = param.attribute("name");
4131             if (paramName.startsWith("meta.") || paramName == "length") {
4132                 prod.removeChild(props.at(j));
4133                 j--;
4134             }
4135         }
4136     }
4137
4138     QDomNodeList entries = doc.elementsByTagName("entry");
4139     for (int i = 0; i < entries.count(); i++) {
4140         QDomElement entry = entries.at(i).toElement();
4141         int in = entry.attribute("in").toInt();
4142         int out = entry.attribute("out").toInt();
4143         in = factor * in + 0.5;
4144         out = factor * out + 0.5;
4145         entry.setAttribute("in", in);
4146         entry.setAttribute("out", out);
4147     }
4148
4149     QDomNodeList blanks = doc.elementsByTagName("blank");
4150     for (int i = 0; i < blanks.count(); i++) {
4151         QDomElement blank = blanks.at(i).toElement();
4152         int length = blank.attribute("length").toInt();
4153         length = factor * length + 0.5;
4154         blank.setAttribute("length", QString::number(length));
4155     }
4156
4157     QDomNodeList filters = doc.elementsByTagName("filter");
4158     for (int i = 0; i < filters.count(); i++) {
4159         QDomElement filter = filters.at(i).toElement();
4160         int in = filter.attribute("in").toInt();
4161         int out = filter.attribute("out").toInt();
4162         in = factor * in + 0.5;
4163         out = factor * out + 0.5;
4164         filter.setAttribute("in", in);
4165         filter.setAttribute("out", out);
4166     }
4167
4168     QDomNodeList transitions = doc.elementsByTagName("transition");
4169     for (int i = 0; i < transitions.count(); i++) {
4170         QDomElement transition = transitions.at(i).toElement();
4171         int in = transition.attribute("in").toInt();
4172         int out = transition.attribute("out").toInt();
4173         in = factor * in + 0.5;
4174         out = factor * out + 0.5;
4175         transition.setAttribute("in", in);
4176         transition.setAttribute("out", out);
4177         QDomNodeList props = transition.childNodes();
4178         for (int j = 0; j < props.count(); j++) {
4179             QDomElement param =  props.at(j).toElement();
4180             QString paramName = param.attribute("name");
4181             if (paramName == "geometry") {
4182                 QString geom = param.firstChild().nodeValue();
4183                 QStringList keys = geom.split(';');
4184                 QStringList newKeys;
4185                 for (int k = 0; k < keys.size(); ++k) {
4186                     if (keys.at(k).contains('=')) {
4187                         int pos = keys.at(k).section('=', 0, 0).toInt();
4188                         pos = factor * pos + 0.5;
4189                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4190                     } else newKeys.append(keys.at(k));
4191                 }
4192                 param.firstChild().setNodeValue(newKeys.join(";"));
4193             }
4194         }
4195     }
4196     QDomElement root = doc.documentElement();
4197     if (!root.isNull()) {
4198         QDomElement tractor = root.firstChildElement("tractor");
4199         int out = tractor.attribute("out").toInt();
4200         out = factor * out + 0.5;
4201         tractor.setAttribute("out", out);
4202         emit durationChanged(out);
4203     }
4204
4205     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4206     return doc.toString();
4207 }
4208
4209
4210 void Render::sendFrameUpdate()
4211 {
4212     if (m_mltProducer) {
4213         Mlt::Frame * frame = m_mltProducer->get_frame();
4214         emitFrameUpdated(*frame);
4215         delete frame;
4216     }
4217 }
4218
4219 Mlt::Producer* Render::getProducer()
4220 {
4221     return m_mltProducer;
4222 }
4223
4224 const QString Render::activeClipId()
4225 {
4226     if (m_mltProducer) return m_mltProducer->get("id");
4227     return QString();
4228 }
4229
4230 #include "renderer.moc"
4231