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