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