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