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