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