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