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