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