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