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