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