]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Cleaning code style of Definitions.
[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     QString playlist;
1417     Mlt::Profile profile((mlt_profile) 0);
1418     Mlt::Consumer xmlConsumer(profile, "xml:kdenlive_playlist");
1419     if (!xmlConsumer.is_valid()) return QString();
1420     m_mltProducer->optimise();
1421     xmlConsumer.set("terminate_on_pause", 1);
1422     Mlt::Producer prod(m_mltProducer->get_producer());
1423     if (!prod.is_valid()) return QString();
1424     bool split = m_isSplitView;
1425     if (split) slotSplitView(false);
1426     xmlConsumer.connect(prod);
1427     xmlConsumer.run();
1428     playlist = QString::fromUtf8(xmlConsumer.get("kdenlive_playlist"));
1429     if (split) slotSplitView(true);
1430     return playlist;
1431 }
1432
1433 bool Render::saveSceneList(QString path, QDomElement kdenliveData)
1434 {
1435     QFile file(path);
1436     QDomDocument doc;
1437     doc.setContent(sceneList(), false);
1438     if (doc.isNull()) return false;
1439     QDomElement root = doc.documentElement();
1440     if (!kdenliveData.isNull() && !root.isNull()) {
1441         // add Kdenlive specific tags
1442         root.appendChild(doc.importNode(kdenliveData, true));
1443     }
1444     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1445         kWarning() << "//////  ERROR writing to file: " << path;
1446         return false;
1447     }
1448     file.write(doc.toString().toUtf8());
1449     if (file.error() != QFile::NoError) {
1450         file.close();
1451         return false;
1452     }
1453     file.close();
1454     return true;
1455 }
1456
1457 void Render::saveZone(KUrl url, QString desc, QPoint zone)
1458 {
1459     Mlt::Consumer xmlConsumer(*m_mltProfile, ("xml:" + url.path()).toUtf8().constData());
1460     m_mltProducer->optimise();
1461     xmlConsumer.set("terminate_on_pause", 1);
1462     if (m_name == Kdenlive::ClipMonitor) {
1463         Mlt::Producer *prod = m_mltProducer->cut(zone.x(), zone.y());
1464         Mlt::Playlist list;
1465         list.insert_at(0, prod, 0);
1466         delete prod;
1467         list.set("title", desc.toUtf8().constData());
1468         xmlConsumer.connect(list);
1469
1470     } else {
1471         //TODO: not working yet, save zone from timeline
1472         Mlt::Producer *p1 = new Mlt::Producer(m_mltProducer->get_producer());
1473         /* Mlt::Service service(p1->parent().get_service());
1474          if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";*/
1475
1476         //Mlt::Producer *prod = p1->cut(zone.x(), zone.y());
1477         //prod->set("title", desc.toUtf8().constData());
1478         xmlConsumer.connect(*p1); //list);
1479     }
1480
1481     xmlConsumer.start();
1482 }
1483
1484
1485 bool Render::saveClip(int track, const GenTime &position, const KUrl &url, const QString &desc)
1486 {
1487     // find clip
1488     Mlt::Service service(m_mltProducer->parent().get_service());
1489     Mlt::Tractor tractor(service);
1490     Mlt::Producer trackProducer(tractor.track(track));
1491     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1492
1493     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
1494     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
1495     if (!clip) {
1496         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1497         return false;
1498     }
1499     
1500     Mlt::Consumer xmlConsumer(*m_mltProfile, ("xml:" + url.path()).toUtf8().constData());
1501     xmlConsumer.set("terminate_on_pause", 1);
1502     Mlt::Playlist list;
1503     list.insert_at(0, clip, 0);
1504     //delete clip;
1505     list.set("title", desc.toUtf8().constData());
1506     xmlConsumer.connect(list);
1507     xmlConsumer.run();
1508     kDebug()<<"// SAVED: "<<url;
1509     return true;
1510 }
1511
1512 double Render::fps() const
1513 {
1514     return m_fps;
1515 }
1516
1517 int Render::volume() const
1518 {
1519     if (!m_mltConsumer || !m_mltProducer) return -1;
1520     return ((int) 100 * m_mltProducer->get_double("meta.volume"));
1521 }
1522
1523 void Render::slotSetVolume(int volume)
1524 {
1525     if (!m_mltConsumer || !m_mltProducer) return;
1526     m_mltProducer->set("meta.volume", (double)volume / 100.0);
1527     //return;
1528     /*osdTimer->stop();
1529     m_mltConsumer->set("refresh", 0);
1530     // Attach filter for on screen display of timecode
1531     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1532     mlt_properties_set_double( properties, "meta.volume", volume );
1533     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
1534     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
1535
1536     if (!KdenliveSettings::osdtimecode()) {
1537     m_mltProducer->detach(*m_osdInfo);
1538     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
1539      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
1540     }*/
1541     //refresh();
1542     //m_osdTimer->setSingleShot(2500);
1543 }
1544
1545 void Render::slotOsdTimeout()
1546 {
1547     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
1548     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
1549     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
1550     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
1551     refresh();
1552 }
1553
1554 void Render::start()
1555 {
1556     m_refreshTimer.stop();
1557     QMutexLocker locker(&m_mutex);
1558     if (m_winid == -1) {
1559         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
1560         return;
1561     }
1562     if (!m_mltConsumer) {
1563         kDebug()<<" / - - - STARTED BEFORE CONSUMER!!!";
1564         return;
1565     }
1566     if (m_mltConsumer->is_stopped()) {
1567         if (m_mltConsumer->start() == -1) {
1568             //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."));
1569             kDebug(QtWarningMsg) << "/ / / / CANNOT START MONITOR";
1570         } else {
1571             m_mltConsumer->purge();
1572             m_mltConsumer->set("refresh", 1);
1573         }
1574     }
1575 }
1576
1577 void Render::stop()
1578 {
1579     requestedSeekPosition = SEEK_INACTIVE;
1580     m_refreshTimer.stop();
1581     QMutexLocker locker(&m_mutex);
1582     m_isActive = false;
1583     if (m_mltProducer == NULL) return;
1584     if (m_mltConsumer) {
1585         m_mltConsumer->set("refresh", 0);
1586         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1587         m_mltConsumer->purge();
1588     }
1589
1590     if (m_mltProducer) {
1591         if (m_isZoneMode) resetZoneMode();
1592         m_mltProducer->set_speed(0.0);
1593     }
1594 }
1595
1596 void Render::stop(const GenTime & startTime)
1597 {
1598     requestedSeekPosition = SEEK_INACTIVE;
1599     m_refreshTimer.stop();
1600     QMutexLocker locker(&m_mutex);
1601     m_isActive = false;
1602     if (m_mltProducer) {
1603         if (m_isZoneMode) resetZoneMode();
1604         m_mltProducer->set_speed(0.0);
1605         m_mltProducer->seek((int) startTime.frames(m_fps));
1606     }
1607     m_mltConsumer->purge();
1608 }
1609
1610 void Render::pause()
1611 {
1612     requestedSeekPosition = SEEK_INACTIVE;
1613     if (!m_mltProducer || !m_mltConsumer || !m_isActive)
1614         return;
1615     m_paused = true;
1616     m_mltProducer->set_speed(0.0);
1617     /*m_mltConsumer->set("refresh", 0);
1618     //if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
1619     m_mltProducer->seek(m_mltConsumer->position());*/
1620 }
1621
1622 void Render::setActiveMonitor()
1623 {
1624     if (!m_isActive) emit activateMonitor(m_name);
1625 }
1626
1627 void Render::switchPlay(bool play)
1628 {
1629     QMutexLocker locker(&m_mutex);
1630     requestedSeekPosition = SEEK_INACTIVE;
1631     if (!m_mltProducer || !m_mltConsumer || !m_isActive)
1632         return;
1633     if (m_isZoneMode) resetZoneMode();
1634     if (play && m_paused) {
1635         if (m_name == Kdenlive::ClipMonitor && m_mltConsumer->position() == m_mltProducer->get_out()) m_mltProducer->seek(0);
1636         m_paused = false;
1637         m_mltProducer->set_speed(1.0);
1638         if (m_mltConsumer->is_stopped()) {
1639             m_mltConsumer->start();
1640         }
1641         m_mltConsumer->set("refresh", 1);
1642     } else if (!play) {
1643         m_paused = true;
1644         if (m_winid == 0) {
1645             // OpenGL consumer
1646             m_mltProducer->set_speed(0.0);
1647         }
1648         else {
1649             // SDL consumer, hack to allow pausing near the end of the playlist
1650             m_mltConsumer->set("refresh", 0);
1651             m_mltConsumer->stop();
1652             m_mltProducer->set_speed(0.0);
1653             m_mltProducer->seek(m_mltConsumer->position());
1654             m_mltConsumer->start();
1655         }
1656     }
1657 }
1658
1659 void Render::play(double speed)
1660 {
1661     requestedSeekPosition = SEEK_INACTIVE;
1662     if (!m_mltProducer || !m_isActive) return;
1663     double current_speed = m_mltProducer->get_speed();
1664     if (current_speed == speed) return;
1665     if (m_isZoneMode) resetZoneMode();
1666     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1667     m_mltProducer->set_speed(speed);
1668     if (m_mltConsumer->is_stopped() && speed != 0) {
1669         m_mltConsumer->start();
1670     }
1671     m_paused = speed == 0;
1672     if (current_speed == 0 && speed != 0) m_mltConsumer->set("refresh", 1);
1673 }
1674
1675 void Render::play(const GenTime & startTime)
1676 {
1677     requestedSeekPosition = SEEK_INACTIVE;
1678     if (!m_mltProducer || !m_mltConsumer || !m_isActive)
1679         return;
1680     m_paused = false;
1681     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1682     m_mltProducer->set_speed(1.0);
1683     m_mltConsumer->set("refresh", 1);
1684 }
1685
1686 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime)
1687 {
1688     requestedSeekPosition = SEEK_INACTIVE;
1689     if (!m_mltProducer || !m_mltConsumer || !m_isActive)
1690         return;
1691     //m_mltProducer->set("eof", "loop");
1692     m_isLoopMode = true;
1693     m_loopStart = startTime;
1694     playZone(startTime, stopTime);
1695 }
1696
1697 void Render::playZone(const GenTime & startTime, const GenTime & stopTime)
1698 {
1699     requestedSeekPosition = SEEK_INACTIVE;
1700     if (!m_mltProducer || !m_mltConsumer || !m_isActive)
1701         return;
1702     m_mltProducer->set("out", (int)(stopTime.frames(m_fps)));
1703     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1704     m_paused = false;
1705     m_mltProducer->set_speed(1.0);
1706     if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1707     m_mltConsumer->set("refresh", 1);
1708     m_isZoneMode = true;
1709 }
1710
1711 void Render::resetZoneMode()
1712 {
1713     if (!m_isZoneMode && !m_isLoopMode) return;
1714     m_mltProducer->set("out", m_mltProducer->get_length());
1715     m_isZoneMode = false;
1716     m_isLoopMode = false;
1717 }
1718
1719 void Render::seekToFrame(int pos)
1720 {
1721     if (!m_mltProducer || !m_isActive)
1722         return;
1723     resetZoneMode();
1724     seek(pos);
1725 }
1726
1727 void Render::seekToFrameDiff(int diff)
1728 {
1729     if (!m_mltProducer || !m_isActive)
1730         return;
1731     resetZoneMode();
1732     if (requestedSeekPosition == SEEK_INACTIVE)
1733         seek(m_mltProducer->position() + diff);
1734     else seek(requestedSeekPosition + diff);
1735 }
1736
1737 void Render::refreshIfActive()
1738 {
1739     if (!m_mltConsumer->is_stopped() && m_mltProducer && m_paused && m_isActive) m_refreshTimer.start();
1740 }
1741
1742 void Render::doRefresh()
1743 {
1744     if (m_mltProducer && m_paused && m_isActive) m_refreshTimer.start();
1745 }
1746
1747 void Render::refresh()
1748 {
1749     m_refreshTimer.stop();
1750     QMutexLocker locker(&m_mutex);
1751     if (!m_mltProducer || !m_isActive)
1752         return;
1753     if (m_mltConsumer) {
1754         if (m_mltConsumer->is_stopped()) m_mltConsumer->start();
1755         m_mltConsumer->set("refresh", 1);
1756         //m_mltConsumer->purge();
1757     }
1758 }
1759
1760 void Render::setDropFrames(bool show)
1761 {
1762     QMutexLocker locker(&m_mutex);
1763     if (m_mltConsumer) {
1764         int dropFrames = KdenliveSettings::mltthreads();
1765         if (show == false) dropFrames = -dropFrames;
1766         m_mltConsumer->stop();
1767         m_mltConsumer->set("real_time", dropFrames);
1768         if (m_mltConsumer->start() == -1) {
1769             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1770         }
1771
1772     }
1773 }
1774
1775 void Render::setConsumerProperty(const QString &name, const QString &value)
1776 {
1777     QMutexLocker locker(&m_mutex);
1778     if (m_mltConsumer) {
1779         m_mltConsumer->stop();
1780         m_mltConsumer->set(name.toUtf8().constData(), value.toUtf8().constData());
1781         if (m_isActive && m_mltConsumer->start() == -1) {
1782             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
1783         }
1784
1785     }
1786 }
1787
1788 bool Render::isPlaying() const
1789 {
1790     if (!m_mltConsumer || m_mltConsumer->is_stopped()) return false;
1791     return !m_paused;
1792 }
1793
1794 double Render::playSpeed() const
1795 {
1796     if (m_mltProducer) return m_mltProducer->get_speed();
1797     return 0.0;
1798 }
1799
1800 GenTime Render::seekPosition() const
1801 {
1802     if (m_mltConsumer) return GenTime((int) m_mltConsumer->position(), m_fps);
1803     //if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1804     else return GenTime();
1805 }
1806
1807 int Render::seekFramePosition() const
1808 {
1809     //if (m_mltProducer) return (int) m_mltProducer->position();
1810     if (m_mltConsumer) return (int) m_mltConsumer->position();
1811     return 0;
1812 }
1813
1814 void Render::emitFrameUpdated(Mlt::Frame& frame)
1815 {
1816     mlt_image_format format = mlt_image_rgb24;
1817     int width = 0;
1818     int height = 0;
1819     const uchar* image = frame.get_image(format, width, height);
1820     QImage qimage(width, height, QImage::Format_RGB888);  //Format_ARGB32_Premultiplied);
1821     memcpy(qimage.scanLine(0), image, width * height * 3);
1822     emit frameUpdated(qimage);
1823 }
1824
1825 int Render::getCurrentSeekPosition() const
1826 {
1827     if (requestedSeekPosition != SEEK_INACTIVE) return requestedSeekPosition;
1828     return (int) m_mltProducer->position();
1829 }
1830
1831 void Render::emitFrameNumber()
1832 {
1833     int currentPos = m_mltConsumer->position();
1834     if (currentPos == requestedSeekPosition) {
1835         requestedSeekPosition = SEEK_INACTIVE;
1836         m_paused = true;
1837     }
1838     emit rendererPosition(currentPos);
1839     if (requestedSeekPosition != SEEK_INACTIVE) {
1840         m_mltConsumer->purge();
1841         m_mltProducer->seek(requestedSeekPosition);
1842         if (m_mltProducer->get_speed() == 0 && !m_paused) {
1843             m_mltConsumer->set("refresh", 1);
1844         }
1845         requestedSeekPosition = SEEK_INACTIVE;
1846     }
1847 }
1848
1849 void Render::emitConsumerStopped(bool forcePause)
1850 {
1851     // This is used to know when the playing stopped
1852     if (m_mltProducer && (forcePause || (!m_paused && m_mltProducer->get_speed() == 0))) {
1853         double pos = m_mltProducer->position();
1854         m_paused = true;
1855         if (m_isLoopMode) play(m_loopStart);
1856         //else if (m_isZoneMode) resetZoneMode();
1857         emit rendererStopped((int) pos);
1858     }
1859 }
1860
1861 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1862 {
1863     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1864 }
1865
1866 void Render::exportCurrentFrame(const KUrl &url, bool /*notify*/)
1867 {
1868     if (!m_mltProducer) {
1869         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1870         return;
1871     }
1872
1873     //int height = 1080;//KdenliveSettings::defaultheight();
1874     //int width = 1940; //KdenliveSettings::displaywidth();
1875     //TODO: rewrite
1876     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1877     /*
1878        QPixmap pix(width, height);
1879        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1880        m_convert.set("forced", mlt_image_rgb24a);
1881        m_mltProducer->attach(m_convert);
1882        Mlt::Frame * frame = m_mltProducer->get_frame();
1883        m_mltProducer->detach(m_convert);
1884        if (frame) {
1885            pix = frameThumbnail(frame, width, height);
1886            delete frame;
1887        }*/
1888     pix.save(url.path(), "PNG");
1889     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1890 }
1891
1892
1893 void Render::showFrame(Mlt::Frame* frame)
1894 {
1895     int currentPos = m_mltConsumer->position();
1896     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1897     emit rendererPosition(currentPos);
1898     if (frame->is_valid()) {
1899         mlt_image_format format = mlt_image_rgb24;
1900         int width = 0;
1901         int height = 0;
1902         const uchar* image = frame->get_image(format, width, height);
1903         QImage qimage(width, height, QImage::Format_RGB888); //Format_ARGB32_Premultiplied);
1904         memcpy(qimage.scanLine(0), image, width * height * 3);
1905         if (analyseAudio) showAudio(*frame);
1906         delete frame;
1907         emit showImageSignal(qimage);
1908         if (sendFrameForAnalysis) {
1909             emit frameUpdated(qimage);
1910         }
1911     } else delete frame;
1912     showFrameSemaphore.release();
1913     emit checkSeeking();
1914 }
1915
1916 void Render::slotCheckSeeking()
1917 {
1918     if (requestedSeekPosition != SEEK_INACTIVE) {
1919         m_mltProducer->seek(requestedSeekPosition);
1920         if (m_paused) {
1921             refresh();
1922         }
1923         requestedSeekPosition = SEEK_INACTIVE;
1924     }
1925 }
1926
1927 void Render::disablePreview(bool disable)
1928 {
1929     if (m_mltConsumer) {
1930         m_mltConsumer->stop();
1931         m_mltConsumer->set("preview_off", (int) disable);
1932         m_mltConsumer->set("refresh", 0);
1933         m_mltConsumer->start();
1934     }
1935 }
1936
1937 void Render::showAudio(Mlt::Frame& frame)
1938 {
1939     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1940         return;
1941     }
1942
1943     mlt_audio_format audio_format = mlt_audio_s16;
1944     //FIXME: should not be hardcoded..
1945     int freq = 48000;
1946     int num_channels = 2;
1947     int samples = 0;
1948     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1949
1950     if (!data) {
1951         return;
1952     }
1953
1954     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1955     // So the vector is of size samples*channels.
1956     QVector<int16_t> sampleVector(samples*num_channels);
1957     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1958
1959     if (samples > 0) {
1960         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1961     }
1962 }
1963
1964 /*
1965  * MLT playlist direct manipulation.
1966  */
1967
1968 void Render::mltCheckLength(Mlt::Tractor *tractor)
1969 {
1970     //kDebug()<<"checking track length: "<<track<<"..........";
1971
1972     int trackNb = tractor->count();
1973     int duration = 0;
1974     int trackDuration;
1975     if (m_isZoneMode) resetZoneMode();
1976     if (trackNb == 1) {
1977         Mlt::Producer trackProducer(tractor->track(0));
1978         duration = trackProducer.get_playtime() - 1;
1979         m_mltProducer->set("out", duration);
1980         emit durationChanged(duration);
1981         return;
1982     }
1983     while (trackNb > 1) {
1984         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1985         trackDuration = trackProducer.get_playtime() - 1;
1986         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1987         if (trackDuration > duration) duration = trackDuration;
1988         trackNb--;
1989     }
1990
1991     Mlt::Producer blackTrackProducer(tractor->track(0));
1992
1993     if (blackTrackProducer.get_playtime() - 1 != duration) {
1994         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1995         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1996         if (blackclip && blackclip->is_blank()) {
1997             delete blackclip;
1998             blackclip = NULL;
1999         }
2000
2001         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
2002             if (blackclip) delete blackclip;
2003             blackTrackPlaylist.clear();
2004             m_blackClip->set("length", duration + 1);
2005             m_blackClip->set("out", duration);
2006             blackclip = m_blackClip->cut(0, duration);
2007             blackTrackPlaylist.insert_at(0, blackclip, 1);
2008         } else {
2009             if (duration > blackclip->parent().get_length()) {
2010                 blackclip->parent().set("length", duration + 1);
2011                 blackclip->parent().set("out", duration);
2012                 blackclip->set("length", duration + 1);
2013             }
2014             blackTrackPlaylist.resize_clip(0, 0, duration);
2015         }
2016
2017         delete blackclip;
2018         if (m_mltConsumer->position() > duration) {
2019             m_mltConsumer->purge();
2020             m_mltProducer->seek(duration);
2021         }
2022         m_mltProducer->set("out", duration);
2023         emit durationChanged(duration);
2024     }
2025 }
2026
2027 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
2028 {
2029     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
2030     QLocale locale;
2031     // We want a slowmotion producer
2032     double speed = element.attribute("speed", "1.0").toDouble();
2033     int strobe = element.attribute("strobe", "1").toInt();
2034     QString url = QString::fromUtf8(prod->get("resource"));
2035     url.append('?' + locale.toString(speed));
2036     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2037     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2038     if (!slowprod || slowprod->get_producer() == NULL) {
2039         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2040         if (strobe > 1) slowprod->set("strobe", strobe);
2041         QString id = prod->parent().get("id");
2042         if (id.contains('_')) id = id.section('_', 0, 0);
2043         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
2044         if (strobe > 1) producerid.append(':' + QString::number(strobe));
2045         slowprod->set("id", producerid.toUtf8().constData());
2046         m_slowmotionProducers.insert(url, slowprod);
2047     }
2048     return slowprod;
2049 }
2050
2051 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
2052 {
2053     m_refreshTimer.stop();
2054     if (m_mltProducer == NULL) {
2055         kDebug() << "PLAYLIST NOT INITIALISED //////";
2056         return -1;
2057     }
2058     if (prod == NULL) {
2059         kDebug() << "Cannot insert clip without producer //////";
2060         return -1;
2061     }
2062     Mlt::Producer parentProd(m_mltProducer->parent());
2063     if (parentProd.get_producer() == NULL) {
2064         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2065         return -1;
2066     }
2067
2068     Mlt::Service service(parentProd.get_service());
2069     if (service.type() != tractor_type) {
2070         kWarning() << "// TRACTOR PROBLEM";
2071         return -1;
2072     }
2073     Mlt::Tractor tractor(service);
2074     if (info.track > tractor.count() - 1) {
2075         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
2076         return -1;
2077     }
2078     service.lock();
2079     Mlt::Producer trackProducer(tractor.track(info.track));
2080     int trackDuration = trackProducer.get_playtime() - 1;
2081     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2082     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
2083     prod = checkSlowMotionProducer(prod, element);
2084     if (prod == NULL || !prod->is_valid()) {
2085         service.unlock();
2086         return -1;
2087     }
2088
2089     int cutPos = (int) info.cropStart.frames(m_fps);
2090     if (cutPos < 0) cutPos = 0;
2091     int insertPos = (int) info.startPos.frames(m_fps);
2092     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
2093     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
2094     if (overwrite && (insertPos < trackDuration)) {
2095         // Replace zone with blanks
2096         //trackPlaylist.split_at(insertPos, true);
2097         trackPlaylist.remove_region(insertPos, cutDuration + 1);
2098         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2099         trackPlaylist.insert_blank(clipIndex, cutDuration);
2100     } else if (push) {
2101         trackPlaylist.split_at(insertPos, true);
2102         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2103         trackPlaylist.insert_blank(clipIndex, cutDuration);
2104     }
2105     trackPlaylist.consolidate_blanks(0);
2106     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
2107     delete clip;
2108     /*if (QString(prod->get("transparency")).toInt() == 1)
2109         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
2110
2111     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
2112     service.unlock();
2113     /*tractor.multitrack()->refresh();
2114     tractor.refresh();*/
2115     return 0;
2116 }
2117
2118
2119 bool Render::mltCutClip(int track, const GenTime &position)
2120 {
2121     Mlt::Service service(m_mltProducer->parent().get_service());
2122     if (service.type() != tractor_type) {
2123         kWarning() << "// TRACTOR PROBLEM";
2124         return false;
2125     }
2126
2127     Mlt::Tractor tractor(service);
2128     Mlt::Producer trackProducer(tractor.track(track));
2129     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2130
2131
2132     /* // Display playlist info
2133     kDebug()<<"////////////  BEFORE";
2134     for (int i = 0; i < trackPlaylist.count(); ++i) {
2135     int blankStart = trackPlaylist.clip_start(i);
2136     int blankDuration = trackPlaylist.clip_length(i) - 1;
2137     QString blk;
2138     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2139     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2140     }*/
2141
2142     int cutPos = (int) position.frames(m_fps);
2143
2144     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
2145     if (trackPlaylist.is_blank(clipIndex)) {
2146         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
2147         return false;
2148     }
2149     service.lock();
2150     int clipStart = trackPlaylist.clip_start(clipIndex);
2151     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
2152     service.unlock();
2153
2154     // duplicate effects
2155     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
2156     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
2157     
2158     if (original == NULL || clip == NULL) {
2159         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
2160         return false;
2161     }
2162
2163     Mlt::Service clipService(original->get_service());
2164     Mlt::Service dupService(clip->get_service());
2165
2166
2167     delete original;
2168     delete clip;
2169     int ct = 0;
2170     Mlt::Filter *filter = clipService.filter(ct);
2171     while (filter) {
2172         // Only duplicate Kdenlive filters, and skip the fade in effects
2173         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
2174             // looks like there is no easy way to duplicate a filter,
2175             // so we will create a new one and duplicate its properties
2176             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
2177             if (dup && dup->is_valid()) {
2178                 Mlt::Properties entries(filter->get_properties());
2179                 for (int i = 0; i < entries.count(); ++i) {
2180                     dup->set(entries.get_name(i), entries.get(i));
2181                 }
2182                 dupService.attach(*dup);
2183             }
2184         }
2185         ct++;
2186         filter = clipService.filter(ct);
2187     }
2188     return true;
2189     /* // Display playlist info
2190     kDebug()<<"////////////  AFTER";
2191     for (int i = 0; i < trackPlaylist.count(); ++i) {
2192     int blankStart = trackPlaylist.clip_start(i);
2193     int blankDuration = trackPlaylist.clip_length(i) - 1;
2194     QString blk;
2195     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2196     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2197     }*/
2198
2199 }
2200
2201 Mlt::Tractor *Render::lockService()
2202 {
2203     // we are going to replace some clips, purge consumer
2204     if (!m_mltProducer) return NULL;
2205     QMutexLocker locker(&m_mutex);
2206     if (m_mltConsumer) {
2207         m_mltConsumer->purge();
2208     }
2209     Mlt::Service service(m_mltProducer->parent().get_service());
2210     if (service.type() != tractor_type) {
2211         return NULL;
2212     }
2213     service.lock();
2214     return new Mlt::Tractor(service);
2215
2216 }
2217
2218 void Render::unlockService(Mlt::Tractor *tractor)
2219 {
2220     if (tractor) {
2221         delete tractor;
2222     }
2223     if (!m_mltProducer) return;
2224     Mlt::Service service(m_mltProducer->parent().get_service());
2225     if (service.type() != tractor_type) {
2226         kWarning() << "// TRACTOR PROBLEM";
2227         return;
2228     }
2229     service.unlock();
2230 }
2231
2232 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
2233 {
2234     // TODO: optimize
2235     if (prod == NULL || tractor == NULL) {
2236         kDebug() << "Cannot update clip with null producer //////";
2237         return false;
2238     }
2239
2240     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
2241     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2242     int startPos = info.startPos.frames(m_fps);
2243     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2244     if (trackPlaylist.is_blank(clipIndex)) {
2245         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
2246         return false;
2247     }
2248     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2249     // keep effects
2250     QList <Mlt::Filter *> filtersList;
2251     Mlt::Service sourceService(clip->get_service());
2252     int ct = 0;
2253     Mlt::Filter *filter = sourceService.filter(ct);
2254     while (filter) {
2255         if (filter->get_int("kdenlive_ix") != 0) {
2256             filtersList.append(filter);
2257         }
2258         ct++;
2259         filter = sourceService.filter(ct);
2260     }
2261     delete clip;
2262     clip = trackPlaylist.replace_with_blank(clipIndex);
2263     delete clip;
2264     prod = checkSlowMotionProducer(prod, element);
2265     if (prod == NULL || !prod->is_valid()) {
2266         return false;
2267     }
2268
2269     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
2270     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
2271     Mlt::Service destService(clip2->get_service());
2272     delete clip2;
2273
2274     if (!filtersList.isEmpty()) {
2275         for (int i = 0; i < filtersList.count(); ++i)
2276             destService.attach(*(filtersList.at(i)));
2277     }
2278     return true;
2279 }
2280
2281
2282 bool Render::mltRemoveClip(int track, GenTime position)
2283 {
2284     m_refreshTimer.stop();
2285     
2286     Mlt::Service service(m_mltProducer->parent().get_service());
2287     if (service.type() != tractor_type) {
2288         kWarning() << "// TRACTOR PROBLEM";
2289         return false;
2290     }
2291     service.lock();
2292     Mlt::Tractor tractor(service);
2293     Mlt::Producer trackProducer(tractor.track(track));
2294     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2295     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2296
2297     if (trackPlaylist.is_blank(clipIndex)) {
2298         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
2299         service.unlock();
2300         return false;
2301     }
2302     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2303     if (clip) delete clip;
2304     trackPlaylist.consolidate_blanks(0);
2305
2306     /* // Display playlist info
2307     kDebug()<<"////  AFTER";
2308     for (int i = 0; i < trackPlaylist.count(); ++i) {
2309     int blankStart = trackPlaylist.clip_start(i);
2310     int blankDuration = trackPlaylist.clip_length(i) - 1;
2311     QString blk;
2312     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2313     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2314     }*/
2315     service.unlock();
2316     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
2317     return true;
2318 }
2319
2320 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
2321 {
2322     if (!m_mltProducer) {
2323         kDebug() << "PLAYLIST NOT INITIALISED //////";
2324         return 0;
2325     }
2326     Mlt::Producer parentProd(m_mltProducer->parent());
2327     if (parentProd.get_producer() == NULL) {
2328         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2329         return 0;
2330     }
2331
2332     Mlt::Service service(parentProd.get_service());
2333     Mlt::Tractor tractor(service);
2334     int insertPos = pos.frames(m_fps);
2335
2336     Mlt::Producer trackProducer(tractor.track(track));
2337     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2338     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2339     if (clipIndex == trackPlaylist.count()) {
2340         // We are after the end of the playlist
2341         return -1;
2342     }
2343     if (!trackPlaylist.is_blank(clipIndex)) return 0;
2344     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
2345     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
2346 }
2347
2348 int Render::mltTrackDuration(int track)
2349 {
2350     if (!m_mltProducer) {
2351         kDebug() << "PLAYLIST NOT INITIALISED //////";
2352         return -1;
2353     }
2354     Mlt::Producer parentProd(m_mltProducer->parent());
2355     if (parentProd.get_producer() == NULL) {
2356         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2357         return -1;
2358     }
2359
2360     Mlt::Service service(parentProd.get_service());
2361     Mlt::Tractor tractor(service);
2362
2363     Mlt::Producer trackProducer(tractor.track(track));
2364     return trackProducer.get_playtime() - 1;
2365 }
2366
2367 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
2368 {
2369     if (!m_mltProducer) {
2370         kDebug() << "PLAYLIST NOT INITIALISED //////";
2371         return;
2372     }
2373     Mlt::Producer parentProd(m_mltProducer->parent());
2374     if (parentProd.get_producer() == NULL) {
2375         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2376         return;
2377     }
2378     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
2379     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
2380
2381     Mlt::Service service(parentProd.get_service());
2382     Mlt::Tractor tractor(service);
2383     service.lock();
2384     int diff = duration.frames(m_fps);
2385     int offset = timeOffset.frames(m_fps);
2386     int insertPos;
2387
2388     if (track != -1) {
2389         // insert space in one track only
2390         Mlt::Producer trackProducer(tractor.track(track));
2391         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2392         insertPos = trackClipStartList.value(track);
2393         if (insertPos != -1) {
2394             insertPos += offset;
2395             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2396             if (diff > 0) {
2397                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2398             } else {
2399                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2400                 if (!trackPlaylist.is_blank(clipIndex)) {
2401                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2402                 }
2403                 int position = trackPlaylist.clip_start(clipIndex);
2404                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2405                 if (blankDuration + diff == 0) {
2406                     trackPlaylist.remove(clipIndex);
2407                 } else trackPlaylist.remove_region(position, -diff);
2408             }
2409             trackPlaylist.consolidate_blanks(0);
2410         }
2411         // now move transitions
2412         mlt_service serv = m_mltProducer->parent().get_service();
2413         mlt_service nextservice = mlt_service_get_producer(serv);
2414         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2415         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2416         QString resource = mlt_properties_get(properties, "mlt_service");
2417
2418         while (mlt_type == "transition") {
2419             mlt_transition tr = (mlt_transition) nextservice;
2420             int currentTrack = mlt_transition_get_b_track(tr);
2421             int currentIn = (int) mlt_transition_get_in(tr);
2422             int currentOut = (int) mlt_transition_get_out(tr);
2423             insertPos = trackTransitionStartList.value(track);
2424             if (insertPos != -1) {
2425                 insertPos += offset;
2426                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2427                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2428                 }
2429             }
2430             nextservice = mlt_service_producer(nextservice);
2431             if (nextservice == NULL) break;
2432             properties = MLT_SERVICE_PROPERTIES(nextservice);
2433             mlt_type = mlt_properties_get(properties, "mlt_type");
2434             resource = mlt_properties_get(properties, "mlt_service");
2435         }
2436     } else {
2437         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2438             Mlt::Producer trackProducer(tractor.track(trackNb));
2439             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2440
2441             //int clipNb = trackPlaylist.count();
2442             insertPos = trackClipStartList.value(trackNb);
2443             if (insertPos != -1) {
2444                 insertPos += offset;
2445
2446                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2447                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2448                         for (int i = 0; i < clipNb; ++i) {
2449                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2450                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2451                      kDebug()<<"-------------";
2452                  }
2453                  kDebug()<<"END-------------";*/
2454
2455
2456                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2457                 if (diff > 0) {
2458                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2459                 } else {
2460                     if (!trackPlaylist.is_blank(clipIndex)) {
2461                         clipIndex --;
2462                     }
2463                     if (!trackPlaylist.is_blank(clipIndex)) {
2464                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2465                     }
2466                     int position = trackPlaylist.clip_start(clipIndex);
2467                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2468                     if (diff + blankDuration == 0) {
2469                         trackPlaylist.remove(clipIndex);
2470                     } else trackPlaylist.remove_region(position, - diff);
2471                 }
2472                 trackPlaylist.consolidate_blanks(0);
2473             }
2474         }
2475         // now move transitions
2476         mlt_service serv = m_mltProducer->parent().get_service();
2477         mlt_service nextservice = mlt_service_get_producer(serv);
2478         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2479         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2480         QString resource = mlt_properties_get(properties, "mlt_service");
2481
2482         while (mlt_type == "transition") {
2483             mlt_transition tr = (mlt_transition) nextservice;
2484             int currentIn = (int) mlt_transition_get_in(tr);
2485             int currentOut = (int) mlt_transition_get_out(tr);
2486             int currentTrack = mlt_transition_get_b_track(tr);
2487             insertPos = trackTransitionStartList.value(currentTrack);
2488             if (insertPos != -1) {
2489                 insertPos += offset;
2490                 if (currentOut > insertPos && resource != "mix") {
2491                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2492                 }
2493             }
2494             nextservice = mlt_service_producer(nextservice);
2495             if (nextservice == NULL) break;
2496             properties = MLT_SERVICE_PROPERTIES(nextservice);
2497             mlt_type = mlt_properties_get(properties, "mlt_type");
2498             resource = mlt_properties_get(properties, "mlt_service");
2499         }
2500     }
2501     service.unlock();
2502     mltCheckLength(&tractor);
2503     m_mltConsumer->set("refresh", 1);
2504 }
2505
2506
2507 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2508 {
2509     if (source == dest) return;
2510     Mlt::Service sourceService(source->get_service());
2511     Mlt::Service destService(dest->get_service());
2512
2513     // move all effects to the correct producer
2514     int ct = 0;
2515     Mlt::Filter *filter = sourceService.filter(ct);
2516     while (filter) {
2517         if (filter->get_int("kdenlive_ix") != 0) {
2518             sourceService.detach(*filter);
2519             destService.attach(*filter);
2520         } else ct++;
2521         filter = sourceService.filter(ct);
2522     }
2523 }
2524
2525 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2526 {
2527     int newLength = 0;
2528     Mlt::Service service(m_mltProducer->parent().get_service());
2529     if (service.type() != tractor_type) {
2530         kWarning() << "// TRACTOR PROBLEM";
2531         return -1;
2532     }
2533
2534     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2535     Mlt::Tractor tractor(service);
2536     Mlt::Producer trackProducer(tractor.track(info.track));
2537     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2538     int startPos = info.startPos.frames(m_fps);
2539     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2540     int clipLength = trackPlaylist.clip_length(clipIndex);
2541
2542     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2543     if (original == NULL) {
2544         return -1;
2545     }
2546     if (!original->is_valid() || original->is_blank()) {
2547         // invalid clip
2548         delete original;
2549         return -1;
2550     }
2551     Mlt::Producer clipparent = original->parent();
2552     if (!clipparent.is_valid() || clipparent.is_blank()) {
2553         // invalid clip
2554         delete original;
2555         return -1;
2556     }
2557
2558     QString serv = clipparent.get("mlt_service");
2559     QString id = clipparent.get("id");
2560     if (speed <= 0 && speed > -1) speed = 1.0;
2561     //kDebug() << "CLIP SERVICE: " << serv;
2562     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2563         service.lock();
2564         QString url = QString::fromUtf8(clipparent.get("resource"));
2565         url.append('?' + m_locale.toString(speed));
2566         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2567         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2568         if (!slowprod || slowprod->get_producer() == NULL) {
2569             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2570             if (strobe > 1) slowprod->set("strobe", strobe);
2571             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2572             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2573             slowprod->set("id", producerid.toUtf8().constData());
2574             // copy producer props
2575             double ar = original->parent().get_double("force_aspect_ratio");
2576             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2577             double fps = original->parent().get_double("force_fps");
2578             if (fps != 0.0) slowprod->set("force_fps", fps);
2579             int threads = original->parent().get_int("threads");
2580             if (threads != 0) slowprod->set("threads", threads);
2581             if (original->parent().get("force_progressive"))
2582                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2583             if (original->parent().get("force_tff"))
2584                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2585             int ix = original->parent().get_int("video_index");
2586             if (ix != 0) slowprod->set("video_index", ix);
2587             int colorspace = original->parent().get_int("force_colorspace");
2588             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2589             int full_luma = original->parent().get_int("set.force_full_luma");
2590             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2591             m_slowmotionProducers.insert(url, slowprod);
2592         }
2593         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2594         trackPlaylist.consolidate_blanks(0);
2595
2596         // Check that the blank space is long enough for our new duration
2597         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2598         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2599         Mlt::Producer *cut;
2600         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2601             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2602             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2603         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2604
2605         // move all effects to the correct producer
2606         mltPasteEffects(clip, cut);
2607         trackPlaylist.insert_at(startPos, cut, 1);
2608         delete cut;
2609         delete clip;
2610         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2611         newLength = trackPlaylist.clip_length(clipIndex);
2612         service.unlock();
2613     } else if (speed == 1.0 && strobe < 2) {
2614         if (!prod || !prod->is_valid()) {
2615             kDebug()<<"// Something is wrong with producer";
2616             return -1;
2617         }
2618         service.lock();
2619
2620         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2621         trackPlaylist.consolidate_blanks(0);
2622
2623         // Check that the blank space is long enough for our new duration
2624         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2625         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2626
2627         Mlt::Producer *cut;
2628         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2629         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2630             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2631             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2632         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2633
2634         // move all effects to the correct producer
2635         mltPasteEffects(clip, cut);
2636
2637         trackPlaylist.insert_at(startPos, cut, 1);
2638         delete cut;
2639         delete clip;
2640         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2641         newLength = trackPlaylist.clip_length(clipIndex);
2642         service.unlock();
2643
2644     } else if (serv == "framebuffer") {
2645         service.lock();
2646         QString url = QString::fromUtf8(clipparent.get("resource"));
2647         url = url.section('?', 0, 0);
2648         url.append('?' + m_locale.toString(speed));
2649         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2650         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2651         if (!slowprod || slowprod->get_producer() == NULL) {
2652             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2653             slowprod->set("strobe", strobe);
2654             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2655             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2656             slowprod->set("id", producerid.toUtf8().constData());
2657             // copy producer props
2658             double ar = original->parent().get_double("force_aspect_ratio");
2659             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2660             double fps = original->parent().get_double("force_fps");
2661             if (fps != 0.0) slowprod->set("force_fps", fps);
2662             if (original->parent().get("force_progressive"))
2663                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2664             if (original->parent().get("force_tff"))
2665                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2666             int threads = original->parent().get_int("threads");
2667             if (threads != 0) slowprod->set("threads", threads);
2668             int ix = original->parent().get_int("video_index");
2669             if (ix != 0) slowprod->set("video_index", ix);
2670             int colorspace = original->parent().get_int("force_colorspace");
2671             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2672             int full_luma = original->parent().get_int("set.force_full_luma");
2673             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2674             m_slowmotionProducers.insert(url, slowprod);
2675         }
2676         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2677         trackPlaylist.consolidate_blanks(0);
2678
2679         GenTime duration = speedIndependantInfo.cropDuration / speed;
2680         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2681
2682         // Check that the blank space is long enough for our new duration
2683         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2684         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2685
2686         Mlt::Producer *cut;
2687         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2688             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2689             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2690         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2691
2692         // move all effects to the correct producer
2693         mltPasteEffects(clip, cut);
2694
2695         trackPlaylist.insert_at(startPos, cut, 1);
2696         delete cut;
2697         delete clip;
2698         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2699         newLength = trackPlaylist.clip_length(clipIndex);
2700
2701         service.unlock();
2702     }
2703     delete original;
2704     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2705     return newLength;
2706 }
2707
2708 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2709 {
2710     Mlt::Service service(m_mltProducer->parent().get_service());
2711     bool success = false;
2712     Mlt::Tractor tractor(service);
2713     Mlt::Producer trackProducer(tractor.track(track));
2714     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2715     Mlt::Service clipService(trackPlaylist.get_service());
2716
2717     service.lock();
2718     int ct = 0;
2719     Mlt::Filter *filter = clipService.filter(ct);
2720     while (filter) {
2721         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2722             if (clipService.detach(*filter) == 0) success = true;
2723         } else if (updateIndex) {
2724             // Adjust the other effects index
2725             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2726             ct++;
2727         } else ct++;
2728         filter = clipService.filter(ct);
2729     }
2730     service.unlock();
2731     refresh();
2732     return success;
2733 }
2734
2735 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2736 {
2737     if (position < GenTime()) {
2738         // Remove track effect
2739         return mltRemoveTrackEffect(track, index, updateIndex);
2740     }
2741     Mlt::Service service(m_mltProducer->parent().get_service());
2742     bool success = false;
2743     Mlt::Tractor tractor(service);
2744     Mlt::Producer trackProducer(tractor.track(track));
2745     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2746
2747     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2748     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2749     if (!clip) {
2750         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2751         return false;
2752     }
2753
2754     Mlt::Service clipService(clip->get_service());
2755     int duration = clip->get_playtime();
2756     if (doRefresh) {
2757         // Check if clip is visible in monitor
2758         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2759         if (diff < 0 || diff > duration) doRefresh = false;
2760     }
2761     delete clip;
2762
2763     service.lock();
2764     int ct = 0;
2765     Mlt::Filter *filter = clipService.filter(ct);
2766     while (filter) {
2767         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2768             if (clipService.detach(*filter) == 0) success = true;
2769             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2770         } else if (updateIndex) {
2771             // Adjust the other effects index
2772             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2773             ct++;
2774         } else ct++;
2775         filter = clipService.filter(ct);
2776     }
2777     service.unlock();
2778     if (doRefresh) refresh();
2779     return success;
2780 }
2781
2782 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2783 {
2784     Mlt::Service service(m_mltProducer->parent().get_service());
2785     Mlt::Tractor tractor(service);
2786     Mlt::Producer trackProducer(tractor.track(track));
2787     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2788     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2789     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2790 }
2791
2792
2793 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2794 {
2795
2796     Mlt::Service service(m_mltProducer->parent().get_service());
2797
2798     Mlt::Tractor tractor(service);
2799     Mlt::Producer trackProducer(tractor.track(track));
2800     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2801
2802     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2803     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2804     if (!clip) {
2805         return false;
2806     }
2807
2808     Mlt::Service clipService(clip->get_service());
2809     int duration = clip->get_playtime();
2810     if (doRefresh) {
2811         // Check if clip is visible in monitor
2812         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2813         if (diff < 0 || diff > duration) doRefresh = false;
2814     }
2815     delete clip;
2816     return mltAddEffect(clipService, params, duration, doRefresh);
2817 }
2818
2819 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2820 {
2821     bool updateIndex = false;
2822     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2823     int ct = 0;
2824     service.lock();
2825
2826     Mlt::Filter *filter = service.filter(ct);
2827     while (filter) {
2828         if (filter->get_int("kdenlive_ix") == filter_ix) {
2829             // A filter at that position already existed, so we will increase all indexes later
2830             updateIndex = true;
2831             break;
2832         }
2833         ct++;
2834         filter = service.filter(ct);
2835     }
2836
2837     if (params.paramValue("id") == "speed") {
2838         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2839         ct = 0;
2840         filter = service.filter(ct);
2841         while (filter) {
2842             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2843                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2844             }
2845             ct++;
2846             filter = service.filter(ct);
2847         }
2848         service.unlock();
2849         if (doRefresh) refresh();
2850         return true;
2851     }
2852
2853
2854     // temporarily remove all effects after insert point
2855     QList <Mlt::Filter *> filtersList;
2856     ct = 0;
2857     filter = service.filter(ct);
2858     while (filter) {
2859         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2860             filtersList.append(filter);
2861             service.detach(*filter);
2862         } else ct++;
2863         filter = service.filter(ct);
2864     }
2865
2866     bool success = addFilterToService(service, params, duration);
2867
2868     // re-add following filters
2869     for (int i = 0; i < filtersList.count(); ++i) {
2870         Mlt::Filter *filter = filtersList.at(i);
2871         if (updateIndex)
2872             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2873         service.attach(*filter);
2874     }
2875     service.unlock();
2876     if (doRefresh) refresh();
2877     return success;
2878 }
2879
2880
2881 bool Render::addFilterToService(Mlt::Service service, EffectsParameterList params, int duration)
2882 {
2883     // create filter
2884     QString tag =  params.paramValue("tag");
2885     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2886     QString kfr = params.paramValue("keyframes");
2887     if (!kfr.isEmpty()) {
2888         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2889         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2890         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2891         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2892         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2893         //double max = params.paramValue("max").toDouble();
2894         double min = params.paramValue("min").toDouble();
2895         double factor = params.paramValue("factor", "1").toDouble();
2896         double paramOffset = params.paramValue("offset", "0").toDouble();
2897         params.removeParam("starttag");
2898         params.removeParam("endtag");
2899         params.removeParam("keyframes");
2900         params.removeParam("min");
2901         params.removeParam("max");
2902         params.removeParam("factor");
2903         params.removeParam("offset");
2904         int offset = 0;
2905         // Special case, only one keyframe, means we want a constant value
2906         if (keyFrames.count() == 1) {
2907             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, qstrdup(tag.toUtf8().constData()));
2908             if (filter && filter->is_valid()) {
2909                 filter->set("kdenlive_id", qstrdup(params.paramValue("id").toUtf8().constData()));
2910                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2911                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2912                 for (int j = 0; j < params.count(); j++) {
2913                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2914                 }
2915                 filter->set("in", x1);
2916                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2917                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2918                 service.attach(*filter);
2919             } else {
2920                 delete[] starttag;
2921                 delete[] endtag;
2922                 kDebug() << "filter is NULL";
2923                 service.unlock();
2924                 return false;
2925             }
2926         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2927             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, qstrdup(tag.toUtf8().constData()));
2928             if (filter && filter->is_valid()) {
2929                 filter->set("kdenlive_id", qstrdup(params.paramValue("id").toUtf8().constData()));
2930                 int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2931                 double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2932                 int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2933                 double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2934                 if (x2 == -1) x2 = duration;
2935
2936                 for (int j = 0; j < params.count(); j++) {
2937                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2938                 }
2939
2940                 filter->set("in", x1);
2941                 filter->set("out", x2);
2942                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2943                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2944                 filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2945                 service.attach(*filter);
2946                 offset = 1;
2947             } else {
2948                 delete[] starttag;
2949                 delete[] endtag;
2950                 kDebug() << "filter is NULL";
2951                 service.unlock();
2952                 return false;
2953             }
2954         }
2955         delete[] starttag;
2956         delete[] endtag;
2957     } else {
2958         Mlt::Filter *filter;
2959         QString prefix;
2960         filter = new Mlt::Filter(*m_mltProfile, qstrdup(tag.toUtf8().constData()));
2961         if (filter && filter->is_valid()) {
2962             filter->set("kdenlive_id", qstrdup(params.paramValue("id").toUtf8().constData()));
2963         } else {
2964             kDebug() << "filter is NULL";
2965             service.unlock();
2966             return false;
2967         }
2968         params.removeParam("kdenlive_id");
2969         if (params.hasParam("_sync_in_out")) {
2970             // This effect must sync in / out with parent clip
2971             params.removeParam("_sync_in_out");
2972             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2973         }
2974
2975         for (int j = 0; j < params.count(); j++) {
2976             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2977         }
2978
2979         if (tag == "sox") {
2980             QString effectArgs = params.paramValue("id").section('_', 1);
2981
2982             params.removeParam("id");
2983             params.removeParam("kdenlive_ix");
2984             params.removeParam("tag");
2985             params.removeParam("disable");
2986             params.removeParam("region");
2987
2988             for (int j = 0; j < params.count(); j++) {
2989                 effectArgs.append(' ' + params.at(j).value());
2990             }
2991             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2992             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2993         }
2994         // attach filter to the clip
2995         service.attach(*filter);
2996     }
2997     return true;
2998 }
2999
3000 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
3001 {
3002     Mlt::Service service(m_mltProducer->parent().get_service());
3003     Mlt::Tractor tractor(service);
3004     Mlt::Producer trackProducer(tractor.track(track));
3005     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3006     Mlt::Service clipService(trackPlaylist.get_service());
3007     int ct = 0;
3008     QString index = params.paramValue("kdenlive_ix");
3009     QString tag =  params.paramValue("tag");
3010
3011     Mlt::Filter *filter = clipService.filter(ct);
3012     while (filter) {
3013         if (filter->get_int("kdenlive_ix") == index.toInt()) {
3014             break;
3015         }
3016         ct++;
3017         filter = clipService.filter(ct);
3018     }
3019
3020     if (!filter) {
3021         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
3022         // filter was not found, it was probably a disabled filter, so add it to the correct place...
3023
3024         bool success = false;//mltAddTrackEffect(track, params);
3025         return success;
3026     }
3027     QString prefix;
3028     QString ser = filter->get("mlt_service");
3029     if (ser == "region") prefix = "filter0.";
3030     service.lock();
3031     for (int j = 0; j < params.count(); j++) {
3032         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
3033     }
3034     service.unlock();
3035
3036     refresh();
3037     return true;
3038 }
3039
3040 bool Render::mltEditEffect(int track, const GenTime &position, EffectsParameterList params)
3041 {
3042     int index = params.paramValue("kdenlive_ix").toInt();
3043     QString tag =  params.paramValue("tag");
3044
3045     if (!params.paramValue("keyframes").isEmpty() || (tag == "affine" && params.hasParam("background")) || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
3046         // This is a keyframe effect, to edit it, we remove it and re-add it.
3047         bool success = mltRemoveEffect(track, position, index, false);
3048         //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
3049         if (position < GenTime())
3050             success = mltAddTrackEffect(track, params);
3051         else
3052             success = mltAddEffect(track, position, params);
3053         //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
3054         return success;
3055     }
3056     if (position < GenTime()) {
3057         return mltEditTrackEffect(track, params);
3058     }
3059     // find filter
3060     Mlt::Service service(m_mltProducer->parent().get_service());
3061     Mlt::Tractor tractor(service);
3062     Mlt::Producer trackProducer(tractor.track(track));
3063     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3064
3065     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3066     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3067     if (!clip) {
3068         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3069         return false;
3070     }
3071
3072     int duration = clip->get_playtime();
3073     bool doRefresh = true;
3074     // Check if clip is visible in monitor
3075     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3076     if (diff < 0 || diff > duration)
3077         doRefresh = false;
3078     int ct = 0;
3079
3080     Mlt::Filter *filter = clip->filter(ct);
3081     while (filter) {
3082         if (filter->get_int("kdenlive_ix") == index) {
3083             break;
3084         }
3085         ct++;
3086         filter = clip->filter(ct);
3087     }
3088
3089     if (!filter) {
3090         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
3091         // filter was not found, it was probably a disabled filter, so add it to the correct place...
3092
3093         bool success = mltAddEffect(track, position, params);
3094         return success;
3095     }
3096     ct = 0;
3097     QString ser = filter->get("mlt_service");
3098     QList <Mlt::Filter *> filtersList;
3099     service.lock();
3100     if (ser != tag) {
3101         // Effect service changes, delete effect and re-add it
3102         clip->detach(*filter);
3103
3104         // Delete all effects after deleted one
3105         filter = clip->filter(ct);
3106         while (filter) {
3107             if (filter->get_int("kdenlive_ix") > index) {
3108                 filtersList.append(filter);
3109                 clip->detach(*filter);
3110             }
3111             else ct++;
3112             filter = clip->filter(ct);
3113         }
3114
3115         // re-add filter
3116         addFilterToService(*clip, params, clip->get_playtime());
3117         delete clip;
3118         service.unlock();
3119
3120         if (doRefresh)
3121             refresh();
3122         return true;
3123     }
3124     if (params.hasParam("_sync_in_out")) {
3125         // This effect must sync in / out with parent clip
3126         params.removeParam("_sync_in_out");
3127         filter->set_in_and_out(clip->get_in(), clip->get_out());
3128     }
3129
3130     for (int j = 0; j < params.count(); ++j) {
3131         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
3132     }
3133     
3134     for (int j = 0; j < filtersList.count(); ++j) {
3135         clip->attach(*(filtersList.at(j)));
3136     }
3137
3138     delete clip;
3139     service.unlock();
3140
3141     if (doRefresh)
3142         refresh();
3143     return true;
3144 }
3145
3146 bool Render::mltEnableEffects(int track, const GenTime &position, const QList <int> &effectIndexes, bool disable)
3147 {
3148     if (position < GenTime()) {
3149         return mltEnableTrackEffects(track, effectIndexes, disable);
3150     }
3151     // find filter
3152     Mlt::Service service(m_mltProducer->parent().get_service());
3153     Mlt::Tractor tractor(service);
3154     Mlt::Producer trackProducer(tractor.track(track));
3155     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3156
3157     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3158     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3159     if (!clip) {
3160         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3161         return false;
3162     }
3163
3164     int duration = clip->get_playtime();
3165     bool doRefresh = true;
3166     // Check if clip is visible in monitor
3167     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3168     if (diff < 0 || diff > duration)
3169         doRefresh = false;
3170     int ct = 0;
3171
3172     Mlt::Filter *filter = clip->filter(ct);
3173     while (filter) {
3174         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3175             filter->set("disable", (int) disable);
3176         }
3177         ct++;
3178         filter = clip->filter(ct);
3179     }
3180
3181     delete clip;
3182     service.unlock();
3183
3184     if (doRefresh) refresh();
3185     return true;
3186 }
3187
3188 bool Render::mltEnableTrackEffects(int track, const QList <int> &effectIndexes, bool disable)
3189 {
3190     Mlt::Service service(m_mltProducer->parent().get_service());
3191     Mlt::Tractor tractor(service);
3192     Mlt::Producer trackProducer(tractor.track(track));
3193     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3194     Mlt::Service clipService(trackPlaylist.get_service());
3195     int ct = 0;
3196
3197     Mlt::Filter *filter = clipService.filter(ct);
3198     while (filter) {
3199         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3200             filter->set("disable", (int) disable);
3201         }
3202         ct++;
3203         filter = clipService.filter(ct);
3204     }
3205     service.unlock();
3206
3207     refresh();
3208     return true;
3209 }
3210
3211 void Render::mltUpdateEffectPosition(int track, const GenTime &position, int oldPos, int newPos)
3212 {
3213     Mlt::Service service(m_mltProducer->parent().get_service());
3214     Mlt::Tractor tractor(service);
3215     Mlt::Producer trackProducer(tractor.track(track));
3216     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3217
3218     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3219     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3220     if (!clip) {
3221         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3222         return;
3223     }
3224
3225     Mlt::Service clipService(clip->get_service());
3226     int duration = clip->get_playtime();
3227     bool doRefresh = true;
3228     // Check if clip is visible in monitor
3229     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3230     if (diff < 0 || diff > duration) doRefresh = false;
3231     delete clip;
3232
3233     int ct = 0;
3234     Mlt::Filter *filter = clipService.filter(ct);
3235     while (filter) {
3236         int pos = filter->get_int("kdenlive_ix");
3237         if (pos == oldPos) {
3238             filter->set("kdenlive_ix", newPos);
3239         } else ct++;
3240         filter = clipService.filter(ct);
3241     }
3242     if (doRefresh) refresh();
3243 }
3244
3245 void Render::mltMoveEffect(int track, const GenTime &position, int oldPos, int newPos)
3246 {
3247     if (position < GenTime()) {
3248         mltMoveTrackEffect(track, oldPos, newPos);
3249         return;
3250     }
3251     Mlt::Service service(m_mltProducer->parent().get_service());
3252     Mlt::Tractor tractor(service);
3253     Mlt::Producer trackProducer(tractor.track(track));
3254     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3255
3256     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3257     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3258     if (!clip) {
3259         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3260         return;
3261     }
3262
3263     Mlt::Service clipService(clip->get_service());
3264     int duration = clip->get_playtime();
3265     bool doRefresh = true;
3266     // Check if clip is visible in monitor
3267     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3268     if (diff < 0 || diff > duration) doRefresh = false;
3269     delete clip;
3270
3271     int ct = 0;
3272     QList <Mlt::Filter *> filtersList;
3273     Mlt::Filter *filter = clipService.filter(ct);
3274     bool found = false;
3275     if (newPos > oldPos) {
3276         while (filter) {
3277             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3278                 filter->set("kdenlive_ix", newPos);
3279                 filtersList.append(filter);
3280                 clipService.detach(*filter);
3281                 filter = clipService.filter(ct);
3282                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3283                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3284                     ct++;
3285                     filter = clipService.filter(ct);
3286                 }
3287                 found = true;
3288             }
3289             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3290                 filtersList.append(filter);
3291                 clipService.detach(*filter);
3292             } else ct++;
3293             filter = clipService.filter(ct);
3294         }
3295     } else {
3296         while (filter) {
3297             if (filter->get_int("kdenlive_ix") == oldPos) {
3298                 filter->set("kdenlive_ix", newPos);
3299                 filtersList.append(filter);
3300                 clipService.detach(*filter);
3301             } else ct++;
3302             filter = clipService.filter(ct);
3303         }
3304
3305         ct = 0;
3306         filter = clipService.filter(ct);
3307         while (filter) {
3308             int pos = filter->get_int("kdenlive_ix");
3309             if (pos >= newPos) {
3310                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3311                 filtersList.append(filter);
3312                 clipService.detach(*filter);
3313             } else ct++;
3314             filter = clipService.filter(ct);
3315         }
3316     }
3317
3318     for (int i = 0; i < filtersList.count(); ++i) {
3319         clipService.attach(*(filtersList.at(i)));
3320     }
3321
3322     if (doRefresh) refresh();
3323 }
3324
3325 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
3326 {
3327     Mlt::Service service(m_mltProducer->parent().get_service());
3328     Mlt::Tractor tractor(service);
3329     Mlt::Producer trackProducer(tractor.track(track));
3330     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3331     Mlt::Service clipService(trackPlaylist.get_service());
3332     int ct = 0;
3333     QList <Mlt::Filter *> filtersList;
3334     Mlt::Filter *filter = clipService.filter(ct);
3335     bool found = false;
3336     if (newPos > oldPos) {
3337         while (filter) {
3338             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3339                 filter->set("kdenlive_ix", newPos);
3340                 filtersList.append(filter);
3341                 clipService.detach(*filter);
3342                 filter = clipService.filter(ct);
3343                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3344                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3345                     ct++;
3346                     filter = clipService.filter(ct);
3347                 }
3348                 found = true;
3349             }
3350             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3351                 filtersList.append(filter);
3352                 clipService.detach(*filter);
3353             } else ct++;
3354             filter = clipService.filter(ct);
3355         }
3356     } else {
3357         while (filter) {
3358             if (filter->get_int("kdenlive_ix") == oldPos) {
3359                 filter->set("kdenlive_ix", newPos);
3360                 filtersList.append(filter);
3361                 clipService.detach(*filter);
3362             } else ct++;
3363             filter = clipService.filter(ct);
3364         }
3365
3366         ct = 0;
3367         filter = clipService.filter(ct);
3368         while (filter) {
3369             int pos = filter->get_int("kdenlive_ix");
3370             if (pos >= newPos) {
3371                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3372                 filtersList.append(filter);
3373                 clipService.detach(*filter);
3374             } else ct++;
3375             filter = clipService.filter(ct);
3376         }
3377     }
3378
3379     for (int i = 0; i < filtersList.count(); ++i) {
3380         clipService.attach(*(filtersList.at(i)));
3381     }
3382     refresh();
3383 }
3384
3385 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration, bool refresh)
3386 {
3387     Mlt::Service service(m_mltProducer->parent().get_service());
3388     Mlt::Tractor tractor(service);
3389     Mlt::Producer trackProducer(tractor.track(info.track));
3390     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3391
3392     /* // Display playlist info
3393     kDebug()<<"////////////  BEFORE RESIZE";
3394     for (int i = 0; i < trackPlaylist.count(); ++i) {
3395     int blankStart = trackPlaylist.clip_start(i);
3396     int blankDuration = trackPlaylist.clip_length(i) - 1;
3397     QString blk;
3398     if (trackPlaylist.is_blank(i)) blk = "(blank)";
3399     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
3400     }*/
3401
3402     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
3403         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3404         return false;
3405     }
3406     service.lock();
3407     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
3408     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
3409     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3410
3411     int previousStart = clip->get_in();
3412     int newDuration = (int) clipDuration.frames(m_fps) - 1;
3413     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
3414
3415     int currentOut = newDuration + previousStart;
3416     if (currentOut > clip->get_length()) {
3417         clip->parent().set("length", currentOut + 1);
3418         clip->parent().set("out", currentOut);
3419         clip->set("length", currentOut + 1);
3420     }
3421
3422     /*if (newDuration > clip->get_out()) {
3423         clip->parent().set_in_and_out(0, newDuration + 1);
3424         clip->set_in_and_out(0, newDuration + 1);
3425     }*/
3426     delete clip;
3427     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
3428     trackPlaylist.consolidate_blanks(0);
3429     // skip to next clip
3430     clipIndex++;
3431     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
3432     if (diff > 0) {
3433         // clip was made longer, trim next blank if there is one.
3434         if (clipIndex < trackPlaylist.count()) {
3435             // If this is not the last clip in playlist
3436             if (trackPlaylist.is_blank(clipIndex)) {
3437                 int blankStart = trackPlaylist.clip_start(clipIndex);
3438                 int blankDuration = trackPlaylist.clip_length(clipIndex);
3439                 if (diff > blankDuration) {
3440                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
3441                 }
3442                 if (diff - blankDuration == 0) {
3443                     trackPlaylist.remove(clipIndex);
3444                 } else trackPlaylist.remove_region(blankStart, diff);
3445             } else {
3446                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
3447             }
3448         }
3449     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
3450     trackPlaylist.consolidate_blanks(0);
3451     service.unlock();
3452
3453     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
3454     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3455         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
3456         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3457         ItemInfo transpinfo;
3458         transpinfo.startPos = info.startPos;
3459         transpinfo.endPos = info.startPos + clipDuration;
3460         transpinfo.track = info.track;
3461         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3462     }*/
3463     if (refresh) m_mltConsumer->set("refresh", 1);
3464     return true;
3465 }
3466
3467 void Render::mltChangeTrackState(int track, bool mute, bool blind)
3468 {
3469     Mlt::Service service(m_mltProducer->parent().get_service());
3470     Mlt::Tractor tractor(service);
3471     Mlt::Producer trackProducer(tractor.track(track));
3472
3473     // Make sure muting will not produce problems with our audio mixing transition,
3474     // because audio mixing is done between each track and the lowest one
3475     bool audioMixingBroken = false;
3476     if (mute && trackProducer.get_int("hide") < 2 ) {
3477         // We mute a track with sound
3478         if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3479         kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
3480     }
3481     else if (!mute && trackProducer.get_int("hide") > 1 ) {
3482         // We un-mute a previously muted track
3483         if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3484     }
3485
3486     if (mute) {
3487         if (blind) trackProducer.set("hide", 3);
3488         else trackProducer.set("hide", 2);
3489     } else if (blind) {
3490         trackProducer.set("hide", 1);
3491     } else {
3492         trackProducer.set("hide", 0);
3493     }
3494     if (audioMixingBroken) fixAudioMixing(tractor);
3495
3496     tractor.multitrack()->refresh();
3497     tractor.refresh();
3498     refresh();
3499 }
3500
3501 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3502 {
3503     for (int i = 1; i < tractor.count(); ++i) {
3504         Mlt::Producer trackProducer(tractor.track(i));
3505         if (trackProducer.get_int("hide") < 2) return i;
3506     }
3507     return tractor.count() - 1;
3508 }
3509
3510 void Render::fixAudioMixing(Mlt::Tractor tractor)
3511 {
3512     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3513     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3514
3515     mlt_service serv = m_mltProducer->parent().get_service();
3516     Mlt::Field *field = tractor.field();
3517     mlt_service_lock(serv);
3518
3519     mlt_service nextservice = mlt_service_get_producer(serv);
3520     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3521     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3522     QString resource = mlt_properties_get(properties, "mlt_service");
3523
3524     mlt_service nextservicetodisconnect;
3525     // Delete all audio mixing transitions
3526     while (mlt_type == "transition") {
3527         if (resource == "mix") {
3528             nextservicetodisconnect = nextservice;
3529             nextservice = mlt_service_producer(nextservice);
3530             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3531         }
3532         else nextservice = mlt_service_producer(nextservice);
3533         if (nextservice == NULL) break;
3534         properties = MLT_SERVICE_PROPERTIES(nextservice);
3535         mlt_type = mlt_properties_get(properties, "mlt_type");
3536         resource = mlt_properties_get(properties, "mlt_service");
3537     }
3538
3539     // Re-add correct audio transitions
3540     for (int i = lowestTrack + 1; i < tractor.count(); ++i) {
3541         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3542         transition->set("always_active", 1);
3543         transition->set("combine", 1);
3544         transition->set("internal_added", 237);
3545         field->plant_transition(*transition, lowestTrack, i);
3546     }
3547     mlt_service_unlock(serv);
3548 }
3549
3550 bool Render::mltResizeClipCrop(ItemInfo info, GenTime newCropStart)
3551 {
3552     Mlt::Service service(m_mltProducer->parent().get_service());
3553     int newCropFrame = (int) newCropStart.frames(m_fps);
3554     Mlt::Tractor tractor(service);
3555     Mlt::Producer trackProducer(tractor.track(info.track));
3556     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3557     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3558         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3559         return false;
3560     }
3561     service.lock();
3562     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3563     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3564     if (clip == NULL) {
3565         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3566         service.unlock();
3567         return false;
3568     }
3569     int previousStart = clip->get_in();
3570     int previousOut = clip->get_out();
3571     delete clip;
3572     if (previousStart == newCropFrame) {
3573         kDebug() << "////////  No ReSIZING Required";
3574         service.unlock();
3575         return true;
3576     }
3577     int frameOffset = newCropFrame - previousStart;
3578     trackPlaylist.resize_clip(clipIndex, newCropFrame, previousOut + frameOffset);
3579     service.unlock();
3580     m_mltConsumer->set("refresh", 1);
3581     return true;
3582 }
3583
3584 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3585 {
3586     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3587     Mlt::Service service(m_mltProducer->parent().get_service());
3588     int moveFrame = (int) diff.frames(m_fps);
3589     Mlt::Tractor tractor(service);
3590     Mlt::Producer trackProducer(tractor.track(info.track));
3591     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3592     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3593         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3594         return false;
3595     }
3596     service.lock();
3597     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3598     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3599     if (clip == NULL || clip->is_blank()) {
3600         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3601         service.unlock();
3602         return false;
3603     }
3604     int previousStart = clip->get_in();
3605     int previousOut = clip->get_out();
3606
3607     previousStart += moveFrame;
3608
3609     if (previousStart < 0) {
3610         // this is possible for images and color clips
3611         previousOut -= previousStart;
3612         previousStart = 0;
3613     }
3614
3615     int length = previousOut + 1;
3616     if (length > clip->get_length()) {
3617         clip->parent().set("length", length + 1);
3618         clip->parent().set("out", length);
3619         clip->set("length", length + 1);
3620     }
3621     delete clip;
3622
3623     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3624     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3625     if (moveFrame > 0) {
3626         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3627     } else {
3628         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3629         int blankIndex = clipIndex - 1;
3630         int blankLength = trackPlaylist.clip_length(blankIndex);
3631         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3632         if (! trackPlaylist.is_blank(blankIndex)) {
3633             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3634         }
3635         if (blankLength + moveFrame == 0)
3636             trackPlaylist.remove(blankIndex);
3637         else
3638             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3639     }
3640     trackPlaylist.consolidate_blanks(0);
3641     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3642         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3643         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3644         ItemInfo transpinfo;
3645         transpinfo.startPos = info.startPos + diff;
3646         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3647         transpinfo.track = info.track;
3648         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3649     }*/
3650     //m_mltConsumer->set("refresh", 1);
3651     service.unlock();
3652     m_mltConsumer->set("refresh", 1);
3653     return true;
3654 }
3655
3656 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3657 {
3658     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3659 }
3660
3661
3662 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3663 {
3664     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3665         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3666         return false;
3667     }
3668
3669     Mlt::Producer trackProducer(tractor->track(track));
3670     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3671     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3672     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3673     if (clipProducer == NULL || clipProducer->is_blank()) {
3674         kDebug() << "// ERROR UPDATING CLIP PROD";
3675         delete clipProducer;
3676         return false;
3677     }
3678     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3679     if (!clip || !clip->is_valid()) {
3680         if (clip) delete clip;
3681         delete clipProducer;
3682         return false;
3683     }
3684     // move all effects to the correct producer
3685     mltPasteEffects(clipProducer, clip);
3686     trackPlaylist.insert_at(pos, clip, 1);
3687     delete clip;
3688     delete clipProducer;
3689     return true;
3690 }
3691
3692 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3693 {
3694     Mlt::Service service(m_mltProducer->parent().get_service());
3695     if (service.type() != tractor_type) {
3696         kWarning() << "// TRACTOR PROBLEM";
3697         return false;
3698     }
3699
3700     Mlt::Tractor tractor(service);
3701     service.lock();
3702     Mlt::Producer trackProducer(tractor.track(startTrack));
3703     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3704     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3705     int clipDuration = trackPlaylist.clip_length(clipIndex);
3706     bool checkLength = false;
3707     if (endTrack == startTrack) {
3708         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3709         if (!clipProducer) {
3710             kDebug() << "// Cannot get clip at index: "<<clipIndex<<" / "<< moveStart;
3711             service.unlock();
3712             return false;
3713         }
3714         trackPlaylist.consolidate_blanks(0);
3715         if (!overwrite) {
3716             bool success = true;
3717             if (!trackPlaylist.is_blank_at(moveEnd) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
3718                 success = false;
3719             }
3720             else {
3721                 // Check that the destination region is empty
3722                 trackPlaylist.consolidate_blanks(0);
3723                 int destinationIndex = trackPlaylist.get_clip_index_at(moveEnd);
3724                 if (destinationIndex < trackPlaylist.count() - 1) {
3725                     // We are not at the end of the track
3726                     int blankSize = trackPlaylist.blanks_from(destinationIndex, 1);
3727                     // Make sure we have enough place to insert clip
3728                     if (blankSize - clipDuration - (moveEnd - trackPlaylist.clip_start(destinationIndex)) < 0) success = false;
3729                 }
3730             }
3731             if (!success) {
3732                 if (clipProducer) {
3733                     trackPlaylist.insert_at(moveStart, clipProducer, 1);
3734                     delete clipProducer;
3735                 }
3736                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3737                 service.unlock();
3738                 return false;
3739             }
3740         } else {
3741             // Overwrite mode
3742             trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3743             int ix = trackPlaylist.get_clip_index_at(moveEnd);
3744             trackPlaylist.insert_blank(ix, clipProducer->get_playtime() - 1);
3745             trackPlaylist.consolidate_blanks(0);
3746         }
3747         int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3748         if (newIndex == -1) {
3749             kDebug()<<"// CANNOT MOVE CLIP TO: "<<moveEnd;
3750             trackPlaylist.insert_at(moveStart, clipProducer, 1);
3751             delete clipProducer;
3752             service.unlock();
3753             return false;
3754         }
3755         trackPlaylist.consolidate_blanks(0);
3756         delete clipProducer;
3757         if (newIndex + 1 >= trackPlaylist.count()) checkLength = true;
3758     } else {
3759         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3760         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3761         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3762             // error, destination is not empty
3763             kDebug() << "Cannot move: Destination is not empty";
3764             service.unlock();
3765             return false;
3766         } else {
3767             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3768             if (!clipProducer || clipProducer->is_blank()) {
3769                 // error, destination is not empty
3770                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3771                 if (clipProducer) delete clipProducer;
3772                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3773                 service.unlock();
3774                 return false;
3775             }
3776             trackPlaylist.consolidate_blanks(0);
3777             destTrackPlaylist.consolidate_blanks(1);
3778             Mlt::Producer *clip;
3779             // check if we are moving a slowmotion producer
3780             QString serv = clipProducer->parent().get("mlt_service");
3781             QString currentid = clipProducer->parent().get("id");
3782             if (serv == "framebuffer") {
3783                 clip = clipProducer;
3784             } else {
3785                 if (prod == NULL) {
3786                     // Special case: prod is null when using placeholder clips.
3787                     // in that case, use the producer existing in playlist. Note that
3788                     // it will bypass the one producer per track logic and might cause
3789                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3790                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3791                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3792             }
3793
3794             // move all effects to the correct producer
3795             mltPasteEffects(clipProducer, clip);
3796
3797             if (overwrite) {
3798                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3799                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3800                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3801                 destTrackPlaylist.consolidate_blanks(0);
3802             }
3803
3804             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3805
3806             if (clip == clipProducer) {
3807                 delete clip;
3808                 clip = NULL;
3809             } else {
3810                 delete clip;
3811                 delete clipProducer;
3812             }
3813             destTrackPlaylist.consolidate_blanks(0);
3814             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3815                 kDebug() << "//////// moving clip transparency";
3816                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3817             }*/
3818             if (clipIndex > trackPlaylist.count()) checkLength = true;
3819             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3820         }
3821     }
3822     service.unlock();
3823     if (checkLength) mltCheckLength(&tractor);
3824     //askForRefresh();
3825     //m_mltConsumer->set("refresh", 1);
3826     return true;
3827 }
3828
3829
3830 QList <int> Render::checkTrackSequence(int track)
3831 {
3832     QList <int> list;
3833     Mlt::Service service(m_mltProducer->parent().get_service());
3834     if (service.type() != tractor_type) {
3835         kWarning() << "// TRACTOR PROBLEM";
3836         return list;
3837     }
3838     Mlt::Tractor tractor(service);
3839     service.lock();
3840     Mlt::Producer trackProducer(tractor.track(track));
3841     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3842     int clipNb = trackPlaylist.count();
3843     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3844     for (int i = 0; i < clipNb; ++i) {
3845         Mlt::Producer *c = trackPlaylist.get_clip(i);
3846         int pos = trackPlaylist.clip_start(i);
3847         if (!list.contains(pos)) list.append(pos);
3848         pos += c->get_playtime();
3849         if (!list.contains(pos)) list.append(pos);
3850         delete c;
3851     }
3852     return list;
3853 }
3854
3855 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3856 {
3857     int new_in = (int)newIn.frames(m_fps);
3858     int new_out = (int)newOut.frames(m_fps) - 1;
3859     if (new_in >= new_out) return false;
3860     int old_in = (int)oldIn.frames(m_fps);
3861     int old_out = (int)oldOut.frames(m_fps) - 1;
3862
3863     Mlt::Service service(m_mltProducer->parent().get_service());
3864     Mlt::Tractor tractor(service);
3865     Mlt::Field *field = tractor.field();
3866
3867     bool doRefresh = true;
3868     // Check if clip is visible in monitor
3869     int diff = old_out - m_mltProducer->position();
3870     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3871     if (doRefresh) {
3872         diff = new_out - m_mltProducer->position();
3873         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3874     }
3875     service.lock();
3876
3877     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3878     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3879     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3880     QString resource = mlt_properties_get(properties, "mlt_service");
3881     int old_pos = (int)(old_in + old_out) / 2;
3882     bool found = false;
3883
3884     while (mlt_type == "transition") {
3885         Mlt::Transition transition((mlt_transition) nextservice);
3886         nextservice = mlt_service_producer(nextservice);
3887         int currentTrack = transition.get_b_track();
3888         int currentIn = (int) transition.get_in();
3889         int currentOut = (int) transition.get_out();
3890
3891         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3892             found = true;
3893             if (newTrack - startTrack != 0) {
3894                 Mlt::Properties trans_props(transition.get_properties());
3895                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3896                 Mlt::Properties new_trans_props(new_transition.get_properties());
3897                 // We cannot use MLT's property inherit because it also clones internal values like _unique_id which messes up the playlist
3898                 cloneProperties(new_trans_props, trans_props);
3899                 new_transition.set_in_and_out(new_in, new_out);
3900                 field->disconnect_service(transition);
3901                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3902             } else transition.set_in_and_out(new_in, new_out);
3903             break;
3904         }
3905         if (nextservice == NULL) break;
3906         properties = MLT_SERVICE_PROPERTIES(nextservice);
3907         mlt_type = mlt_properties_get(properties, "mlt_type");
3908         resource = mlt_properties_get(properties, "mlt_service");
3909     }
3910     service.unlock();
3911     if (doRefresh) refresh();
3912     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3913     return found;
3914 }
3915
3916 void Render::cloneProperties(Mlt::Properties &dest, Mlt::Properties &source)
3917 {
3918     int count = source.count();
3919     int i = 0;
3920     for ( i = 0; i < count; i ++ )
3921     {
3922         char *value = source.get(i);
3923         if ( value != NULL )
3924         {
3925             char *name = source.get_name( i );
3926             if (name != NULL && name[0] != '_') dest.set(name, value);
3927         }
3928     }
3929 }
3930
3931 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3932 {
3933     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3934     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3935     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3936     QString resource = mlt_properties_get(properties, "mlt_service");
3937     QList <Mlt::Transition *> trList;
3938     mlt_properties insertproperties = tr.get_properties();
3939     QString insertresource = mlt_properties_get(insertproperties, "mlt_service");
3940     bool isMixTransition = insertresource == "mix";
3941
3942     while (mlt_type == "transition") {
3943         Mlt::Transition transition((mlt_transition) nextservice);
3944         nextservice = mlt_service_producer(nextservice);
3945         int aTrack = transition.get_a_track();
3946         int bTrack = transition.get_b_track();
3947         if ((isMixTransition || resource != "mix") && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3948             Mlt::Properties trans_props(transition.get_properties());
3949             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3950             Mlt::Properties new_trans_props(cp->get_properties());
3951             //new_trans_props.inherit(trans_props);
3952             cloneProperties(new_trans_props, trans_props);
3953             trList.append(cp);
3954             field->disconnect_service(transition);
3955         }
3956         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3957
3958         if (nextservice == NULL) break;
3959         properties = MLT_SERVICE_PROPERTIES(nextservice);
3960         mlt_type = mlt_properties_get(properties, "mlt_type");
3961         resource = mlt_properties_get(properties, "mlt_service");
3962     }
3963     field->plant_transition(tr, a_track, b_track);
3964
3965     // re-add upper transitions
3966     for (int i = trList.count() - 1; i >= 0; --i) {
3967         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3968         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3969     }
3970     qDeleteAll(trList);
3971 }
3972
3973 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3974 {
3975     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3976     else {
3977         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3978         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3979         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3980     }
3981
3982     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3983 }
3984
3985 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3986 {
3987     mlt_service serv = m_mltProducer->parent().get_service();
3988     mlt_service_lock(serv);
3989
3990     mlt_service nextservice = mlt_service_get_producer(serv);
3991     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3992     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3993     QString resource = mlt_properties_get(properties, "mlt_service");
3994     int in_pos = (int) in.frames(m_fps);
3995     int out_pos = (int) out.frames(m_fps) - 1;
3996
3997     while (mlt_type == "transition") {
3998         mlt_transition tr = (mlt_transition) nextservice;
3999         int currentTrack = mlt_transition_get_b_track(tr);
4000         int currentBTrack = mlt_transition_get_a_track(tr);
4001         int currentIn = (int) mlt_transition_get_in(tr);
4002         int currentOut = (int) mlt_transition_get_out(tr);
4003
4004         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
4005         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
4006             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
4007             QMap<QString, QString>::Iterator it;
4008             QString key;
4009             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
4010
4011             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
4012             if (currentId != xml.attribute("id")) {
4013                 // The transition ID is not the same, so reset all properties
4014                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
4015                 // Cleanup previous properties
4016                 QStringList permanentProps;
4017                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
4018                 permanentProps << "out" << "a_track" << "b_track";
4019                 for (int i = 0; i < mlt_properties_count(transproperties); ++i) {
4020                     QString propName = mlt_properties_get_name(transproperties, i);
4021                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
4022                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
4023                     }
4024                 }
4025             }
4026
4027             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
4028             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
4029
4030             if (currentBTrack != a_track) {
4031                 mlt_properties_set_int(transproperties, "a_track", a_track);
4032             }
4033             for (it = map.begin(); it != map.end(); ++it) {
4034                 key = it.key();
4035                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
4036                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
4037                 //filter->set("kdenlive_id", id);
4038             }
4039             break;
4040         }
4041         nextservice = mlt_service_producer(nextservice);
4042         if (nextservice == NULL) break;
4043         properties = MLT_SERVICE_PROPERTIES(nextservice);
4044         mlt_type = mlt_properties_get(properties, "mlt_type");
4045         resource = mlt_properties_get(properties, "mlt_service");
4046     }
4047     mlt_service_unlock(serv);
4048     //askForRefresh();
4049     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
4050 }
4051
4052 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
4053 {
4054     mlt_service serv = m_mltProducer->parent().get_service();
4055     mlt_service_lock(serv);
4056
4057     Mlt::Service service(serv);
4058     Mlt::Tractor tractor(service);
4059     Mlt::Field *field = tractor.field();
4060
4061     //if (do_refresh) m_mltConsumer->set("refresh", 0);
4062
4063     mlt_service nextservice = mlt_service_get_producer(serv);
4064     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4065     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4066     QString resource = mlt_properties_get(properties, "mlt_service");
4067
4068     const int old_pos = (int)((in + out).frames(m_fps) / 2);
4069     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
4070
4071     while (mlt_type == "transition") {
4072         mlt_transition tr = (mlt_transition) nextservice;
4073         int currentTrack = mlt_transition_get_b_track(tr);
4074         int currentIn = (int) mlt_transition_get_in(tr);
4075         int currentOut = (int) mlt_transition_get_out(tr);
4076         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
4077
4078         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
4079             mlt_field_disconnect_service(field->get_field(), nextservice);
4080             break;
4081         }
4082         nextservice = mlt_service_producer(nextservice);
4083         if (nextservice == NULL) break;
4084         properties = MLT_SERVICE_PROPERTIES(nextservice);
4085         mlt_type = mlt_properties_get(properties, "mlt_type");
4086         resource = mlt_properties_get(properties, "mlt_service");
4087     }
4088     mlt_service_unlock(serv);
4089     //askForRefresh();
4090     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
4091 }
4092
4093 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(const QDomElement &xml)
4094 {
4095     QDomNodeList attribs = xml.elementsByTagName("parameter");
4096     QMap<QString, QString> map;
4097     for (int i = 0; i < attribs.count(); ++i) {
4098         QDomElement e = attribs.item(i).toElement();
4099         QString name = e.attribute("name");
4100         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
4101         map[name] = e.attribute("default");
4102         if (!e.attribute("value").isEmpty()) {
4103             map[name] = e.attribute("value");
4104         }
4105         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
4106             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
4107             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
4108         }
4109
4110         if (e.attribute("namedesc").contains(';')) {
4111             QString format = e.attribute("format");
4112             QStringList separators = format.split("%d", QString::SkipEmptyParts);
4113             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
4114             QString neu;
4115             QTextStream txtNeu(&neu);
4116             if (values.size() > 0)
4117                 txtNeu << (int)values[0].toDouble();
4118             int i = 0;
4119             for (i = 0; i < separators.size() && i + 1 < values.size(); ++i) {
4120                 txtNeu << separators[i];
4121                 txtNeu << (int)(values[i+1].toDouble());
4122             }
4123             if (i < separators.size())
4124                 txtNeu << separators[i];
4125             map[e.attribute("name")] = neu;
4126         }
4127
4128     }
4129     return map;
4130 }
4131
4132 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
4133 {
4134     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
4135     Mlt::Service service(m_mltProducer->parent().get_service());
4136     Mlt::Tractor tractor(service);
4137     Mlt::Field *field = tractor.field();
4138
4139     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
4140     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
4141     transition->set("transparency", id);
4142     transition->set("fill", 1);
4143     transition->set("internal_added", 237);
4144     field->plant_transition(*transition, transitiontrack, info.track);
4145     refresh();
4146 }
4147
4148 void Render::mltDeleteTransparency(int pos, int track, int id)
4149 {
4150     Mlt::Service service(m_mltProducer->parent().get_service());
4151     Mlt::Tractor tractor(service);
4152     Mlt::Field *field = tractor.field();
4153
4154     //if (do_refresh) m_mltConsumer->set("refresh", 0);
4155     mlt_service serv = m_mltProducer->parent().get_service();
4156
4157     mlt_service nextservice = mlt_service_get_producer(serv);
4158     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4159     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4160     QString resource = mlt_properties_get(properties, "mlt_service");
4161
4162     while (mlt_type == "transition") {
4163         mlt_transition tr = (mlt_transition) nextservice;
4164         int currentTrack = mlt_transition_get_b_track(tr);
4165         int currentIn = (int) mlt_transition_get_in(tr);
4166         int currentOut = (int) mlt_transition_get_out(tr);
4167         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4168         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
4169
4170         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
4171             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
4172             mlt_field_disconnect_service(field->get_field(), nextservice);
4173             break;
4174         }
4175         nextservice = mlt_service_producer(nextservice);
4176         if (nextservice == NULL) break;
4177         properties = MLT_SERVICE_PROPERTIES(nextservice);
4178         mlt_type = mlt_properties_get(properties, "mlt_type");
4179         resource = mlt_properties_get(properties, "mlt_service");
4180     }
4181     //if (do_refresh) m_mltConsumer->set("refresh", 1);
4182 }
4183
4184 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
4185 {
4186     Mlt::Service service(m_mltProducer->parent().get_service());
4187     Mlt::Tractor tractor(service);
4188
4189     service.lock();
4190     m_mltConsumer->set("refresh", 0);
4191
4192     mlt_service serv = m_mltProducer->parent().get_service();
4193     mlt_service nextservice = mlt_service_get_producer(serv);
4194     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4195     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4196     QString resource = mlt_properties_get(properties, "mlt_service");
4197     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
4198     while (mlt_type == "transition") {
4199         mlt_transition tr = (mlt_transition) nextservice;
4200         int currentTrack = mlt_transition_get_b_track(tr);
4201         int currentIn = (int) mlt_transition_get_in(tr);
4202         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
4203         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4204         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
4205         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
4206             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
4207             mlt_transition_set_in_and_out(tr, newStart, newEnd);
4208             break;
4209         }
4210         nextservice = mlt_service_producer(nextservice);
4211         if (nextservice == NULL) break;
4212         properties = MLT_SERVICE_PROPERTIES(nextservice);
4213         mlt_type = mlt_properties_get(properties, "mlt_type");
4214         resource = mlt_properties_get(properties, "mlt_service");
4215     }
4216     service.unlock();
4217     m_mltConsumer->set("refresh", 1);
4218
4219 }
4220
4221 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
4222 {
4223     Mlt::Service service(m_mltProducer->parent().get_service());
4224     Mlt::Tractor tractor(service);
4225
4226     service.lock();
4227     m_mltConsumer->set("refresh", 0);
4228
4229     mlt_service serv = m_mltProducer->parent().get_service();
4230     mlt_service nextservice = mlt_service_get_producer(serv);
4231     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4232     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4233     QString resource = mlt_properties_get(properties, "mlt_service");
4234
4235     while (mlt_type == "transition") {
4236         mlt_transition tr = (mlt_transition) nextservice;
4237         int currentTrack = mlt_transition_get_b_track(tr);
4238         int currentaTrack = mlt_transition_get_a_track(tr);
4239         int currentIn = (int) mlt_transition_get_in(tr);
4240         int currentOut = (int) mlt_transition_get_out(tr);
4241         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4242         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4243         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
4244         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
4245             kDebug() << "//////MOVING";
4246             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
4247             if (endTrack != startTrack) {
4248                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4249                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
4250                 mlt_properties_set_int(properties, "b_track", endTrack);
4251             }
4252             break;
4253         }
4254         nextservice = mlt_service_producer(nextservice);
4255         if (nextservice == NULL) break;
4256         properties = MLT_SERVICE_PROPERTIES(nextservice);
4257         mlt_type = mlt_properties_get(properties, "mlt_type");
4258         resource = mlt_properties_get(properties, "mlt_service");
4259     }
4260     service.unlock();
4261     m_mltConsumer->set("refresh", 1);
4262 }
4263
4264
4265 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
4266 {
4267     if (in >= out) return false;
4268     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
4269     Mlt::Service service(m_mltProducer->parent().get_service());
4270
4271     Mlt::Tractor tractor(service);
4272     Mlt::Field *field = tractor.field();
4273
4274     Mlt::Transition transition(*m_mltProfile, tag.toUtf8().constData());
4275     if (out != GenTime())
4276         transition.set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
4277
4278     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
4279     QMap<QString, QString>::Iterator it;
4280     QString key;
4281     if (xml.attribute("automatic") == "1") transition.set("automatic", 1);
4282     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
4283     if (xml.hasAttribute("id"))
4284         transition.set("kdenlive_id", xml.attribute("id").toUtf8().constData());
4285     if (xml.hasAttribute("force_track"))
4286         transition.set("force_track", xml.attribute("force_track").toInt());
4287
4288     for (it = args.begin(); it != args.end(); ++it) {
4289         key = it.key();
4290         if (!it.value().isEmpty())
4291             transition.set(key.toUtf8().constData(), it.value().toUtf8().constData());
4292         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
4293     }
4294     // attach transition
4295     service.lock();
4296     mltPlantTransition(field, transition, a_track, b_track);
4297     // field->plant_transition(*transition, a_track, b_track);
4298     service.unlock();
4299     if (do_refresh) refresh();
4300     return true;
4301 }
4302
4303 void Render::mltSavePlaylist()
4304 {
4305     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
4306     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
4307     fileConsumer.set("resource", "/tmp/playlist.mlt");
4308
4309     Mlt::Service service(m_mltProducer->get_service());
4310
4311     fileConsumer.connect(service);
4312     fileConsumer.start();
4313 }
4314
4315 const QList <Mlt::Producer *> Render::producersList()
4316 {
4317     QList <Mlt::Producer *> prods;
4318     if (m_mltProducer == NULL) return prods;
4319     Mlt::Service service(m_mltProducer->parent().get_service());
4320     if (service.type() != tractor_type) return prods;
4321     Mlt::Tractor tractor(service);
4322     QStringList ids;
4323
4324     int trackNb = tractor.count();
4325     for (int t = 1; t < trackNb; t++) {
4326         Mlt::Producer *tt = tractor.track(t);
4327         Mlt::Producer trackProducer(tt);
4328         delete tt;
4329         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4330         if (!trackPlaylist.is_valid()) continue;
4331         int clipNb = trackPlaylist.count();
4332         for (int i = 0; i < clipNb; ++i) {
4333             Mlt::Producer *c = trackPlaylist.get_clip(i);
4334             if (c == NULL) continue;
4335             QString prodId = c->parent().get("id");
4336             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
4337                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4338                 if (nprod) {
4339                     ids.append(prodId);
4340                     prods.append(nprod);
4341                 }
4342             }
4343             delete c;
4344         }
4345     }
4346     return prods;
4347 }
4348
4349 void Render::fillSlowMotionProducers()
4350 {
4351     if (m_mltProducer == NULL) return;
4352     Mlt::Service service(m_mltProducer->parent().get_service());
4353     if (service.type() != tractor_type) return;
4354
4355     Mlt::Tractor tractor(service);
4356
4357     int trackNb = tractor.count();
4358     for (int t = 1; t < trackNb; t++) {
4359         Mlt::Producer *tt = tractor.track(t);
4360         Mlt::Producer trackProducer(tt);
4361         delete tt;
4362         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4363         if (!trackPlaylist.is_valid()) continue;
4364         int clipNb = trackPlaylist.count();
4365         for (int i = 0; i < clipNb; ++i) {
4366             Mlt::Producer *c = trackPlaylist.get_clip(i);
4367             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4368             if (nprod) {
4369                 QString id = nprod->parent().get("id");
4370                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
4371                     // this is a slowmotion producer, add it to the list
4372                     QString url = QString::fromUtf8(nprod->get("resource"));
4373                     int strobe = nprod->get_int("strobe");
4374                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
4375                     if (!m_slowmotionProducers.contains(url)) {
4376                         m_slowmotionProducers.insert(url, nprod);
4377                     }
4378                 } else delete nprod;
4379             }
4380             delete c;
4381         }
4382     }
4383 }
4384
4385 QList <TransitionInfo> Render::mltInsertTrack(int ix, bool videoTrack)
4386 {
4387     Mlt::Service service(m_mltProducer->parent().get_service());
4388     if (service.type() != tractor_type) {
4389         kWarning() << "// TRACTOR PROBLEM";
4390         return QList <TransitionInfo> ();
4391     }
4392     blockSignals(true);
4393     service.lock();
4394     Mlt::Tractor tractor(service);
4395     QList <TransitionInfo> transitionInfos;
4396     Mlt::Playlist playlist;
4397     int ct = tractor.count();
4398     if (ix > ct) {
4399         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
4400         ix = ct;
4401     }
4402
4403     int pos = ix;
4404     if (pos < ct) {
4405         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
4406         tractor.set_track(playlist, pos);
4407         Mlt::Producer newProd(tractor.track(pos));
4408         if (!videoTrack) newProd.set("hide", 1);
4409         pos++;
4410         for (; pos <= ct; pos++) {
4411             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
4412             tractor.set_track(*prodToMove, pos);
4413             prodToMove = prodToMove2;
4414         }
4415     } else {
4416         tractor.set_track(playlist, ix);
4417         Mlt::Producer newProd(tractor.track(ix));
4418         if (!videoTrack) newProd.set("hide", 1);
4419     }
4420     checkMaxThreads();
4421
4422     // Move transitions
4423     mlt_service serv = m_mltProducer->parent().get_service();
4424     mlt_service nextservice = mlt_service_get_producer(serv);
4425     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4426     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4427     QString resource = mlt_properties_get(properties, "mlt_service");
4428     Mlt::Field *field = tractor.field();
4429     QList <Mlt::Transition *> trList;
4430
4431     while (mlt_type == "transition") {
4432         if (resource != "mix") {
4433             Mlt::Transition transition((mlt_transition) nextservice);
4434             nextservice = mlt_service_producer(nextservice);
4435             int currentbTrack = transition.get_b_track();
4436             int currentaTrack = transition.get_a_track();
4437             bool trackChanged = false;
4438             bool forceTransitionTrack = false;
4439             if (currentbTrack >= ix) {
4440                 if (currentbTrack == ix && currentaTrack < ix) forceTransitionTrack = true;
4441                 currentbTrack++;
4442                 trackChanged = true;
4443             }
4444             if (currentaTrack >= ix) {
4445                 currentaTrack++;
4446                 trackChanged = true;
4447             }
4448             kDebug()<<"// Newtrans: "<<currentaTrack<<"/"<<currentbTrack;
4449
4450             // disconnect all transitions
4451             Mlt::Properties trans_props(transition.get_properties());
4452             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
4453             Mlt::Properties new_trans_props(cp->get_properties());
4454             cloneProperties(new_trans_props, trans_props);
4455             //new_trans_props.inherit(trans_props);
4456
4457             if (trackChanged) {
4458                 // Transition track needs to be adjusted
4459                 cp->set("a_track", currentaTrack);
4460                 cp->set("b_track", currentbTrack);
4461                 // Check if transition track was changed and needs to be forced
4462                 if (forceTransitionTrack) cp->set("force_track", 1);
4463                 TransitionInfo trInfo;
4464                 trInfo.startPos = GenTime(transition.get_in(), m_fps);
4465                 trInfo.a_track = currentaTrack;
4466                 trInfo.b_track = currentbTrack;
4467                 trInfo.forceTrack = cp->get_int("force_track");
4468                 transitionInfos.append(trInfo);
4469             }
4470             trList.append(cp);
4471             field->disconnect_service(transition);
4472         }
4473         else nextservice = mlt_service_producer(nextservice);
4474         if (nextservice == NULL) break;
4475         properties = MLT_SERVICE_PROPERTIES(nextservice);
4476         mlt_type = mlt_properties_get(properties, "mlt_type");
4477         resource = mlt_properties_get(properties, "mlt_service");
4478     }
4479
4480     // Add audio mix transition to last track
4481     Mlt::Transition transition(*m_mltProfile, "mix");
4482     transition.set("a_track", 1);
4483     transition.set("b_track", ct);
4484     transition.set("always_active", 1);
4485     transition.set("internal_added", 237);
4486     transition.set("combine", 1);
4487     mltPlantTransition(field, transition, 1, ct);
4488     
4489     // re-add transitions
4490     for (int i = trList.count() - 1; i >= 0; --i) {
4491         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
4492     }
4493     qDeleteAll(trList);
4494     
4495     service.unlock();
4496     blockSignals(false);
4497     return transitionInfos;
4498 }
4499
4500
4501 void Render::mltDeleteTrack(int ix)
4502 {
4503     QDomDocument doc;
4504     doc.setContent(sceneList(), false);
4505     int tracksCount = doc.elementsByTagName("track").count() - 1;
4506     QDomNode track = doc.elementsByTagName("track").at(ix);
4507     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
4508     QDomNodeList transitions = doc.elementsByTagName("transition");
4509     for (int i = 0; i < transitions.count(); ++i) {
4510         QDomElement e = transitions.at(i).toElement();
4511         QDomNodeList props = e.elementsByTagName("property");
4512         QMap <QString, QString> mappedProps;
4513         for (int j = 0; j < props.count(); j++) {
4514             QDomElement f = props.at(j).toElement();
4515             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
4516         }
4517         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
4518             tractor.removeChild(transitions.at(i));
4519             --i;
4520         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
4521             // Transition needs to be moved
4522             int a_track = mappedProps.value("a_track").toInt();
4523             int b_track = mappedProps.value("b_track").toInt();
4524             if (a_track > 0 && a_track >= ix) a_track --;
4525             if (b_track == ix) {
4526                 // transition was on the deleted track, so remove it
4527                 tractor.removeChild(transitions.at(i));
4528                 --i;
4529                 continue;
4530             }
4531             if (b_track > 0 && b_track > ix) b_track --;
4532             for (int j = 0; j < props.count(); j++) {
4533                 QDomElement f = props.at(j).toElement();
4534                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
4535                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
4536             }
4537
4538         }
4539     }
4540     tractor.removeChild(track);
4541     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
4542     setSceneList(doc.toString(), m_mltConsumer->position());
4543     emit refreshDocumentProducers(false, false);
4544 }
4545
4546
4547 void Render::updatePreviewSettings()
4548 {
4549     kDebug() << "////// RESTARTING CONSUMER";
4550     if (!m_mltConsumer || !m_mltProducer) return;
4551     if (m_mltProducer->get_playtime() == 0) return;
4552     QMutexLocker locker(&m_mutex);
4553     Mlt::Service service(m_mltProducer->parent().get_service());
4554     if (service.type() != tractor_type) return;
4555
4556     //m_mltConsumer->set("refresh", 0);
4557     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
4558     m_mltConsumer->purge();
4559     QString scene = sceneList();
4560     int pos = 0;
4561     if (m_mltProducer) {
4562         pos = m_mltProducer->position();
4563     }
4564
4565     setSceneList(scene, pos);
4566 }
4567
4568
4569 QString Render::updateSceneListFps(double current_fps, double new_fps, const QString &scene)
4570 {
4571     // Update all frame positions to the new fps value
4572     //WARNING: there are probably some effects or other that hold a frame value
4573     // as parameter and will also need to be updated here!
4574     QDomDocument doc;
4575     doc.setContent(scene);
4576
4577     double factor = new_fps / current_fps;
4578     QDomNodeList producers = doc.elementsByTagName("producer");
4579     for (int i = 0; i < producers.count(); ++i) {
4580         QDomElement prod = producers.at(i).toElement();
4581         prod.removeAttribute("in");
4582         prod.removeAttribute("out");
4583
4584         QDomNodeList props = prod.childNodes();
4585         for (int j = 0; j < props.count(); j++) {
4586             QDomElement param =  props.at(j).toElement();
4587             QString paramName = param.attribute("name");
4588             if (paramName.startsWith("meta.") || paramName == "length") {
4589                 prod.removeChild(props.at(j));
4590                 j--;
4591             }
4592         }
4593     }
4594
4595     QDomNodeList entries = doc.elementsByTagName("entry");
4596     for (int i = 0; i < entries.count(); ++i) {
4597         QDomElement entry = entries.at(i).toElement();
4598         int in = entry.attribute("in").toInt();
4599         int out = entry.attribute("out").toInt();
4600         in = factor * in + 0.5;
4601         out = factor * out + 0.5;
4602         entry.setAttribute("in", in);
4603         entry.setAttribute("out", out);
4604     }
4605
4606     QDomNodeList blanks = doc.elementsByTagName("blank");
4607     for (int i = 0; i < blanks.count(); ++i) {
4608         QDomElement blank = blanks.at(i).toElement();
4609         int length = blank.attribute("length").toInt();
4610         length = factor * length + 0.5;
4611         blank.setAttribute("length", QString::number(length));
4612     }
4613
4614     QDomNodeList filters = doc.elementsByTagName("filter");
4615     for (int i = 0; i < filters.count(); ++i) {
4616         QDomElement filter = filters.at(i).toElement();
4617         int in = filter.attribute("in").toInt();
4618         int out = filter.attribute("out").toInt();
4619         in = factor * in + 0.5;
4620         out = factor * out + 0.5;
4621         filter.setAttribute("in", in);
4622         filter.setAttribute("out", out);
4623     }
4624
4625     QDomNodeList transitions = doc.elementsByTagName("transition");
4626     for (int i = 0; i < transitions.count(); ++i) {
4627         QDomElement transition = transitions.at(i).toElement();
4628         int in = transition.attribute("in").toInt();
4629         int out = transition.attribute("out").toInt();
4630         in = factor * in + 0.5;
4631         out = factor * out + 0.5;
4632         transition.setAttribute("in", in);
4633         transition.setAttribute("out", out);
4634         QDomNodeList props = transition.childNodes();
4635         for (int j = 0; j < props.count(); j++) {
4636             QDomElement param =  props.at(j).toElement();
4637             QString paramName = param.attribute("name");
4638             if (paramName == "geometry") {
4639                 QString geom = param.firstChild().nodeValue();
4640                 QStringList keys = geom.split(';');
4641                 QStringList newKeys;
4642                 for (int k = 0; k < keys.size(); ++k) {
4643                     if (keys.at(k).contains('=')) {
4644                         int pos = keys.at(k).section('=', 0, 0).toInt();
4645                         pos = factor * pos + 0.5;
4646                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4647                     } else newKeys.append(keys.at(k));
4648                 }
4649                 param.firstChild().setNodeValue(newKeys.join(";"));
4650             }
4651         }
4652     }
4653     QDomElement root = doc.documentElement();
4654     if (!root.isNull()) {
4655         QDomElement tractor = root.firstChildElement("tractor");
4656         int out = tractor.attribute("out").toInt();
4657         out = factor * out + 0.5;
4658         tractor.setAttribute("out", out);
4659         emit durationChanged(out);
4660     }
4661
4662     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4663     return doc.toString();
4664 }
4665
4666
4667 void Render::sendFrameUpdate()
4668 {
4669     if (m_mltProducer) {
4670         Mlt::Frame * frame = m_mltProducer->get_frame();
4671         emitFrameUpdated(*frame);
4672         delete frame;
4673     }
4674 }
4675
4676 Mlt::Producer* Render::getProducer()
4677 {
4678     return m_mltProducer;
4679 }
4680
4681 const QString Render::activeClipId()
4682 {
4683     if (m_mltProducer) return m_mltProducer->get("id");
4684     return QString();
4685 }
4686
4687 //static 
4688 bool Render::getBlackMagicDeviceList(KComboBox *devicelist, bool force)
4689 {
4690     if (!force && !KdenliveSettings::decklink_device_found()) return false;
4691     Mlt::Profile profile;
4692     Mlt::Producer bm(profile, "decklink");
4693     int found_devices = 0;
4694     if (bm.is_valid()) {
4695         bm.set("list_devices", 1);
4696         found_devices = bm.get_int("devices");
4697     }
4698     else KdenliveSettings::setDecklink_device_found(false);
4699     if (found_devices <= 0) {
4700         devicelist->setEnabled(false);
4701         return false;
4702     }
4703     KdenliveSettings::setDecklink_device_found(true);
4704     for (int i = 0; i < found_devices; ++i) {
4705         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4706         devicelist->addItem(bm.get(tmp));
4707         delete[] tmp;
4708     }
4709     return true;
4710 }
4711
4712 bool Render::getBlackMagicOutputDeviceList(KComboBox *devicelist, bool force)
4713 {
4714     if (!force && !KdenliveSettings::decklink_device_found()) return false;
4715     Mlt::Profile profile;
4716     Mlt::Consumer bm(profile, "decklink");
4717     int found_devices = 0;
4718     if (bm.is_valid()) {
4719         bm.set("list_devices", 1);;
4720         found_devices = bm.get_int("devices");
4721     }
4722     else KdenliveSettings::setDecklink_device_found(false);
4723     if (found_devices <= 0) {
4724         devicelist->setEnabled(false);
4725         return false;
4726     }
4727     KdenliveSettings::setDecklink_device_found(true);
4728     for (int i = 0; i < found_devices; ++i) {
4729         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4730         devicelist->addItem(bm.get(tmp));
4731         delete[] tmp;
4732     }
4733     return true;
4734 }
4735
4736 void Render::slotMultiStreamProducerFound(const QString &path, QList<int> audio_list, QList<int> video_list, stringMap data)
4737
4738     if (KdenliveSettings::automultistreams()) {
4739         for (int i = 1; i < video_list.count(); ++i) {
4740             int vindex = video_list.at(i);
4741             int aindex = 0;
4742             if (i <= audio_list.count() -1) {
4743                 aindex = audio_list.at(i);
4744             }
4745             data.insert("video_index", QString::number(vindex));
4746             data.insert("audio_index", QString::number(aindex));
4747             data.insert("bypassDuplicate", "1");
4748             emit addClip(KUrl(path), data);
4749         }
4750         return;
4751     }
4752     
4753     int width = 60.0 * m_mltProfile->dar();
4754     int swidth = 60.0 * m_mltProfile->width() / m_mltProfile->height();
4755     if (width % 2 == 1) width++;
4756
4757     KDialog dialog(qApp->activeWindow());
4758     dialog.setCaption("Multi Stream Clip");
4759     dialog.setButtons(KDialog::Ok | KDialog::Cancel);
4760     dialog.setButtonText(KDialog::Ok, i18n("Import selected clips"));
4761     QWidget *content = new QWidget(&dialog);
4762     dialog.setMainWidget(content);
4763     QVBoxLayout *vbox = new QVBoxLayout(content);
4764     QLabel *lab1 = new QLabel(i18n("Additional streams for clip\n %1", path), content);
4765     vbox->addWidget(lab1);
4766     QList <QGroupBox*> groupList;
4767     QList <QComboBox*> comboList;
4768     // We start loading the list at 1, video index 0 should already be loaded
4769     for (int j = 1; j < video_list.count(); j++) {
4770         Mlt::Producer multiprod(* m_mltProfile, path.toUtf8().constData());
4771         multiprod.set("video_index", video_list.at(j));
4772         QImage thumb = KThumb::getFrame(&multiprod, 0, swidth, width, 60);
4773         QGroupBox *streamFrame = new QGroupBox(i18n("Video stream %1", video_list.at(j)), content);
4774         streamFrame->setProperty("vindex", video_list.at(j));
4775         groupList << streamFrame;
4776         streamFrame->setCheckable(true);
4777         streamFrame->setChecked(true);
4778         QVBoxLayout *vh = new QVBoxLayout( streamFrame );
4779         QLabel *iconLabel = new QLabel(content);
4780         iconLabel->setPixmap(QPixmap::fromImage(thumb));
4781         vh->addWidget(iconLabel);
4782         if (audio_list.count() > 1) {
4783             QComboBox *cb = new QComboBox(content);
4784             for (int k = 0; k < audio_list.count(); k++) {
4785                 cb->addItem(i18n("Audio stream %1", audio_list.at(k)), audio_list.at(k));
4786             }
4787             comboList << cb;
4788             cb->setCurrentIndex(qMin(j, audio_list.count() - 1));
4789             vh->addWidget(cb);
4790         }
4791         vbox->addWidget(streamFrame);
4792     }
4793     if (dialog.exec() == QDialog::Accepted) {
4794         // import selected streams
4795         for (int i = 0; i < groupList.count(); ++i) {
4796             if (groupList.at(i)->isChecked()) {
4797                 int vindex = groupList.at(i)->property("vindex").toInt();
4798                 int aindex = comboList.at(i)->itemData(comboList.at(i)->currentIndex()).toInt();
4799                 data.insert("video_index", QString::number(vindex));
4800                 data.insert("audio_index", QString::number(aindex));
4801                 data.insert("bypassDuplicate", "1");
4802                 emit addClip(KUrl(path), data);
4803             }
4804         }
4805     }
4806 }
4807
4808 //static 
4809 bool Render::checkX11Grab()
4810 {
4811     if (KdenliveSettings::rendererpath().isEmpty() || KdenliveSettings::ffmpegpath().isEmpty()) return false;
4812     QProcess p;
4813     QStringList args;
4814     args << "avformat:f-list";
4815     p.start(KdenliveSettings::rendererpath(), args);
4816     if (!p.waitForStarted()) return false;
4817     if (!p.waitForFinished()) return false;
4818     QByteArray result = p.readAllStandardError();
4819     return result.contains("x11grab");
4820 }
4821
4822 #include "renderer.moc"
4823