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