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