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