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