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