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