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