]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Merge branch 'master' of git://anongit.kde.org/kdenlive
[kdenlive] / src / renderer.cpp
1 /***************************************************************************
2                         krender.cpp  -  description
3                            -------------------
4   begin                : Fri Nov 22 2002
5   copyright            : (C) 2002 by Jason Wood
6   email                : jasonwood@blueyonder.co.uk
7   copyright            : (C) 2005 Lucio Flavio Correa
8   email                : lucio.correa@gmail.com
9   copyright            : (C) Marco Gittler
10   email                : g.marco@freenet.de
11   copyright            : (C) 2006 Jean-Baptiste Mardelle
12   email                : jb@kdenlive.org
13
14 ***************************************************************************/
15
16 /***************************************************************************
17  *                                                                         *
18  *   This program is free software; you can redistribute it and/or modify  *
19  *   it under the terms of the GNU General Public License as published by  *
20  *   the Free Software Foundation; either version 2 of the License, or     *
21  *   (at your option) any later version.                                   *
22  *                                                                         *
23  ***************************************************************************/
24
25
26 #include "renderer.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "definitions.h"
30 #include "slideshowclip.h"
31 #include "profilesdialog.h"
32
33 #ifdef USE_BLACKMAGIC
34 #include "blackmagic/devices.h"
35 #endif
36
37 #include <mlt++/Mlt.h>
38
39 #include <KDebug>
40 #include <KStandardDirs>
41 #include <KMessageBox>
42 #include <KLocale>
43 #include <KTemporaryFile>
44
45 #include <QTimer>
46 #include <QDir>
47 #include <QString>
48 #include <QApplication>
49 #include <QtConcurrentRun>
50
51 #include <cstdlib>
52 #include <cstdarg>
53
54 #include <QDebug>
55
56 #define SEEK_INACTIVE (-1)
57
58 static void kdenlive_callback(void* /*ptr*/, int level, const char* fmt, va_list vl)
59 {
60 //     kDebug() << "log level" << level << QString().vsprintf(fmt, vl).simplified();
61     if (level > MLT_LOG_ERROR) return;
62     QString error;
63     QApplication::postEvent(qApp->activeWindow(), new MltErrorEvent(error.vsprintf(fmt, vl).simplified()));
64     va_end(vl);
65 }
66
67
68 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr)
69 {
70     // detect if the producer has finished playing. Is there a better way to do it?
71     self->emitFrameNumber();
72     Mlt::Frame frame(frame_ptr);
73     if (!frame.is_valid()) return;
74     if (self->sendFrameForAnalysis && frame_ptr->convert_image) {
75         self->emitFrameUpdated(frame);
76     }
77     if (self->analyseAudio) {
78         self->showAudio(frame);
79     }
80     if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
81         self->pause();
82         self->emitConsumerStopped();
83     }
84 }
85
86
87 static void consumer_paused(mlt_consumer, Render * self, mlt_frame /*frame_ptr*/)
88 {
89     // detect if the producer has finished playing. Is there a better way to do it?
90     self->emitConsumerStopped();
91 }
92
93
94 static void consumer_gl_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr)
95 {
96     // detect if the producer has finished playing. Is there a better way to do it?
97     Mlt::Frame frame(frame_ptr);
98     self->showFrame(frame);
99     if (frame.get_double("_speed") == 0.0) {
100         self->emitConsumerStopped();
101     } else if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
102         self->pause();
103         self->emitConsumerStopped();
104     }
105 }
106
107 Render::Render(Kdenlive::MONITORID rendererName, int winid, QString profile, QWidget *parent) :
108     AbstractRender(rendererName, parent),
109     requestedSeekPosition(SEEK_INACTIVE),
110     m_name(rendererName),
111     m_mltConsumer(NULL),
112     m_mltProducer(NULL),
113     m_mltProfile(NULL),
114     m_showFrameEvent(NULL),
115     m_pauseEvent(NULL),
116     m_externalConsumer(false),
117     m_isZoneMode(false),
118     m_isLoopMode(false),
119     m_isSplitView(false),
120     m_blackClip(NULL),
121     m_winid(winid)
122 {
123     qRegisterMetaType<stringMap> ("stringMap");
124     analyseAudio = KdenliveSettings::monitor_audio();
125     if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
126     buildConsumer(profile);
127     m_mltProducer = m_blackClip->cut(0, 1);
128     m_mltConsumer->connect(*m_mltProducer);
129     m_mltProducer->set_speed(0.0);
130     m_refreshTimer.setSingleShot(true);
131     m_refreshTimer.setInterval(70);
132     connect(&m_refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
133     connect(this, SIGNAL(multiStreamFound(const QString &,QList<int>,QList<int>,stringMap)), this, SLOT(slotMultiStreamProducerFound(const QString &,QList<int>,QList<int>,stringMap)));
134 }
135
136 Render::~Render()
137 {
138     closeMlt();
139     delete m_mltProfile;
140 }
141
142
143 void Render::closeMlt()
144 {
145     //delete m_osdTimer;
146     m_requestList.clear();
147     m_infoThread.waitForFinished();
148     if (m_showFrameEvent) delete m_showFrameEvent;
149     if (m_pauseEvent) delete m_pauseEvent;
150     if (m_mltConsumer) delete m_mltConsumer;
151     if (m_mltProducer) delete m_mltProducer;
152     /*if (m_mltProducer) {
153         Mlt::Service service(m_mltProducer->parent().get_service());
154         service.lock();
155
156         if (service.type() == tractor_type) {
157             Mlt::Tractor tractor(service);
158             Mlt::Field *field = tractor.field();
159             mlt_service nextservice = mlt_service_get_producer(service.get_service());
160             mlt_service nextservicetodisconnect;
161             mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
162             QString mlt_type = mlt_properties_get(properties, "mlt_type");
163             QString resource = mlt_properties_get(properties, "mlt_service");
164             // Delete all transitions
165             while (mlt_type == "transition") {
166                 nextservicetodisconnect = nextservice;
167                 nextservice = mlt_service_producer(nextservice);
168                 mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
169                 if (nextservice == NULL) break;
170                 properties = MLT_SERVICE_PROPERTIES(nextservice);
171                 mlt_type = mlt_properties_get(properties, "mlt_type");
172                 resource = mlt_properties_get(properties, "mlt_service");
173             }
174
175             delete field;
176             field = NULL;
177         }
178         service.unlock();
179     }*/
180
181     //kDebug() << "// // // CLOSE RENDERER " << m_name;
182     if (m_blackClip) delete m_blackClip;
183     //delete m_osdInfo;
184 }
185
186 void Render::slotSwitchFullscreen()
187 {
188     if (m_mltConsumer) m_mltConsumer->set("full_screen", 1);
189 }
190
191 void Render::buildConsumer(const QString &profileName)
192 {
193     delete m_blackClip;
194     m_blackClip = NULL;
195
196     m_activeProfile = profileName;
197     if (m_mltProfile) {
198         Mlt::Profile tmpProfile(m_activeProfile.toUtf8().constData());
199         m_mltProfile->set_colorspace(tmpProfile.colorspace());
200         m_mltProfile->set_frame_rate(tmpProfile.frame_rate_num(), tmpProfile.frame_rate_den());
201         m_mltProfile->set_height(tmpProfile.height());
202         m_mltProfile->set_width(tmpProfile.width());
203         m_mltProfile->set_progressive(tmpProfile.progressive());
204         m_mltProfile->set_sample_aspect(tmpProfile.sample_aspect_num(), tmpProfile.sample_aspect_den());
205         m_mltProfile->get_profile()->display_aspect_num = tmpProfile.display_aspect_num();
206         m_mltProfile->get_profile()->display_aspect_den = tmpProfile.display_aspect_den();
207     }
208     else {
209         m_mltProfile = new Mlt::Profile(m_activeProfile.toUtf8().constData());
210     }
211     setenv("MLT_PROFILE", m_activeProfile.toUtf8().constData(), 1);
212     m_mltProfile->set_explicit(true);
213
214     m_blackClip = new Mlt::Producer(*m_mltProfile, "colour", "black");
215     m_blackClip->set("id", "black");
216     m_blackClip->set("mlt_type", "producer");
217
218     if (KdenliveSettings::external_display() && m_name != Kdenlive::clipMonitor) {
219 #ifdef USE_BLACKMAGIC
220         // Use blackmagic card for video output
221         QMap< QString, QString > profileProperties = ProfilesDialog::getSettingsFromFile(profileName);
222         int device = KdenliveSettings::blackmagic_output_device();
223         if (device >= 0) {
224             if (BMInterface::isSupportedProfile(device, profileProperties)) {
225                 QString decklink = "decklink:" + QString::number(KdenliveSettings::blackmagic_output_device());
226                 if (!m_mltConsumer) {
227                     m_mltConsumer = new Mlt::Consumer(*m_mltProfile, decklink.toUtf8().constData());
228                     m_showFrameEvent = m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
229                     mlt_log_set_callback(kdenlive_callback);
230                 }
231                 if (m_mltConsumer->is_valid()) {
232                     m_externalConsumer = true;
233                     m_mltConsumer->set("terminate_on_pause", 0);
234                     m_mltConsumer->set("deinterlace_method", "onefield");
235                     m_mltConsumer->set("real_time", KdenliveSettings::mltthreads());
236                 }
237                 if (m_mltConsumer && m_mltConsumer->is_valid()) return;
238             } else KMessageBox::informationList(qApp->activeWindow(), i18n("Your project's profile %1 is not compatible with the blackmagic output card. Please see supported profiles below. Switching to normal video display.", m_mltProfile->description()), BMInterface::supportedModes(KdenliveSettings::blackmagic_output_device()));
239         }
240 #endif
241     }
242     m_externalConsumer = false;
243     QString videoDriver = KdenliveSettings::videodrivername();
244     if (!videoDriver.isEmpty()) {
245         if (videoDriver == "x11_noaccel") {
246             setenv("SDL_VIDEO_YUV_HWACCEL", "0", 1);
247             videoDriver = "x11";
248         } else {
249             unsetenv("SDL_VIDEO_YUV_HWACCEL");
250         }
251     }
252     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
253
254     //m_mltConsumer->set("fullscreen", 1);
255     if (m_winid == 0) {
256         // OpenGL monitor
257         if (!m_mltConsumer) {
258             m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_audio");
259             m_showFrameEvent = m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_gl_frame_show);
260         }
261         m_mltConsumer->set("preview_off", 1);
262         m_mltConsumer->set("preview_format", mlt_image_rgb24a);
263     } else {
264         if (!m_mltConsumer) {
265             m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_preview");
266           m_showFrameEvent = m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
267           m_pauseEvent = m_mltConsumer->listen("consumer-sdl-paused", this, (mlt_listener) consumer_paused);
268         }
269         m_mltConsumer->set("window_id", m_winid);
270     }
271     m_mltConsumer->set("resize", 1);
272     m_mltConsumer->set("terminate_on_pause", 1);
273     m_mltConsumer->set("window_background", KdenliveSettings::window_background().name().toUtf8().constData());
274     m_mltConsumer->set("rescale", "nearest");
275     mlt_log_set_callback(kdenlive_callback);
276
277     QString audioDevice = KdenliveSettings::audiodevicename();
278     if (!audioDevice.isEmpty())
279         m_mltConsumer->set("audio_device", audioDevice.toUtf8().constData());
280
281     if (!videoDriver.isEmpty())
282         m_mltConsumer->set("video_driver", videoDriver.toUtf8().constData());
283
284     QString audioDriver = KdenliveSettings::audiodrivername();
285
286     /*
287     // Disabled because the "auto" detected driver was sometimes wrong
288     if (audioDriver.isEmpty())
289         audioDriver = KdenliveSettings::autoaudiodrivername();
290     */
291
292     if (!audioDriver.isEmpty())
293         m_mltConsumer->set("audio_driver", audioDriver.toUtf8().constData());
294
295     m_mltConsumer->set("progressive", 1);
296     m_mltConsumer->set("audio_buffer", 1024);
297     m_mltConsumer->set("frequency", 48000);
298     m_mltConsumer->set("real_time", KdenliveSettings::mltthreads());
299 }
300
301 Mlt::Producer *Render::invalidProducer(const QString &id)
302 {
303     Mlt::Producer *clip;
304     QString txt = '+' + i18n("Missing clip") + ".txt";
305     char *tmp = qstrdup(txt.toUtf8().constData());
306     clip = new Mlt::Producer(*m_mltProfile, tmp);
307     delete[] tmp;
308     if (clip == NULL) clip = new Mlt::Producer(*m_mltProfile, "colour", "red");
309     else {
310         clip->set("bgcolour", "0xff0000ff");
311         clip->set("pad", "10");
312     }
313     clip->set("id", id.toUtf8().constData());
314     clip->set("mlt_type", "producer");
315     return clip;
316 }
317
318 bool Render::hasProfile(const QString &profileName) const
319 {
320     return m_activeProfile == profileName;
321 }
322
323 int Render::resetProfile(const QString &profileName, bool dropSceneList)
324 {
325     m_refreshTimer.stop();
326     if (m_mltConsumer) {
327         if (m_externalConsumer == KdenliveSettings::external_display()) {
328             if (KdenliveSettings::external_display() && m_activeProfile == profileName) return 1;
329             QString videoDriver = KdenliveSettings::videodrivername();
330             QString currentDriver = m_mltConsumer->get("video_driver");
331             if (getenv("SDL_VIDEO_YUV_HWACCEL") != NULL && currentDriver == "x11") currentDriver = "x11_noaccel";
332             QString background = KdenliveSettings::window_background().name();
333             QString currentBackground = m_mltConsumer->get("window_background");
334             if (m_activeProfile == profileName && currentDriver == videoDriver && background == currentBackground) {
335                 kDebug() << "reset to same profile, nothing to do";
336                 return 1;
337             }
338         }
339
340         if (m_isSplitView) slotSplitView(false);
341         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
342         m_mltConsumer->purge();
343     }
344     QString scene;
345     if (!dropSceneList) scene = sceneList();
346     int pos = 0;
347     double current_fps = m_mltProfile->fps();
348     double current_dar = m_mltProfile->dar();
349     delete m_blackClip;
350     m_blackClip = NULL;
351     m_requestList.clear();
352     m_infoThread.waitForFinished();
353
354     if (m_mltProducer) {
355         pos = m_mltProducer->position();
356
357         Mlt::Service service(m_mltProducer->get_service());
358         if (service.type() == tractor_type) {
359             Mlt::Tractor tractor(service);
360             for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
361                 Mlt::Producer trackProducer(tractor.track(trackNb));
362                 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
363                 trackPlaylist.clear();
364             }
365         }
366
367         delete m_mltProducer;
368     }
369     m_mltProducer = NULL;
370     buildConsumer(profileName);
371     double new_fps = m_mltProfile->fps();
372     double new_dar = m_mltProfile->dar();
373
374     if (!dropSceneList) {
375         // We need to recover our playlist
376         if (current_fps != new_fps) {
377             // fps changed, we must update the scenelist positions
378             scene = updateSceneListFps(current_fps, new_fps, scene);
379         }
380         setSceneList(scene, pos);
381         // producers have changed (different profile), so reset them...
382         emit refreshDocumentProducers(new_dar != current_dar, current_fps != new_fps);
383     }
384     return 1;
385 }
386
387 void Render::seek(GenTime time)
388 {
389     int pos = time.frames(m_fps);
390     seek(pos);
391 }
392
393 void Render::seek(int time)
394 {
395     if (!m_mltProducer)
396         return;
397     if (requestedSeekPosition == SEEK_INACTIVE) {
398         requestedSeekPosition = time;
399         m_mltProducer->seek(time);
400         m_mltConsumer->purge();
401         if (m_mltProducer->get_speed() == 0) {
402             refresh();
403         }
404     }
405     else requestedSeekPosition = time;
406 }
407
408 //static
409 /*QPixmap Render::frameThumbnail(Mlt::Frame *frame, int width, int height, bool border) {
410     QPixmap pix(width, height);
411
412     mlt_image_format format = mlt_image_rgb24a;
413     uint8_t *thumb = frame->get_image(format, width, height);
414     QImage image(thumb, width, height, QImage::Format_ARGB32);
415
416     if (!image.isNull()) {
417         pix = pix.fromImage(image);
418         if (border) {
419             QPainter painter(&pix);
420             painter.drawRect(0, 0, width - 1, height - 1);
421         }
422     } else pix.fill(Qt::black);
423     return pix;
424 }
425 */
426 int Render::frameRenderWidth() const
427 {
428     return m_mltProfile->width();
429 }
430
431 int Render::renderWidth() const
432 {
433     return (int)(m_mltProfile->height() * m_mltProfile->dar() + 0.5);
434 }
435
436 int Render::renderHeight() const
437 {
438     return m_mltProfile->height();
439 }
440
441 QImage Render::extractFrame(int frame_position, QString path, int width, int height)
442 {
443     if (width == -1) {
444         width = frameRenderWidth();
445         height = renderHeight();
446     } else if (width % 2 == 1) width++;
447     int dwidth = height * frameRenderWidth() / renderHeight();
448     if (!path.isEmpty()) {
449         Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile, path.toUtf8().constData());
450         if (producer) {
451             if (producer->is_valid()) {
452                 QImage img = KThumb::getFrame(producer, frame_position, dwidth, width, height);
453                 delete producer;
454                 return img;
455             }
456             else delete producer;
457         }
458     }
459
460     if (!m_mltProducer || !path.isEmpty()) {
461         QImage pix(width, height, QImage::Format_RGB32);
462         pix.fill(Qt::black);
463         return pix;
464     }
465     return KThumb::getFrame(m_mltProducer, frame_position, dwidth, width, height);
466 }
467
468 QPixmap Render::getImageThumbnail(KUrl url, int /*width*/, int /*height*/)
469 {
470     QImage im;
471     QPixmap pixmap;
472     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
473         QString fileType = url.fileName().right(3);
474         QStringList more;
475         QStringList::Iterator it;
476
477         QDir dir(url.directory());
478         QStringList filter;
479         filter << "*." + fileType;
480         filter << "*." + fileType.toUpper();
481         more = dir.entryList(filter, QDir::Files);
482         im.load(url.directory() + '/' + more.at(0));
483     } else im.load(url.path());
484     //pixmap = im.scaled(width, height);
485     return pixmap;
486 }
487
488 double Render::consumerRatio() const
489 {
490     if (!m_mltConsumer) return 1.0;
491     return (m_mltConsumer->get_double("aspect_ratio_num") / m_mltConsumer->get_double("aspect_ratio_den"));
492 }
493
494
495 int Render::getLength()
496 {
497
498     if (m_mltProducer) {
499         // kDebug()<<"//////  LENGTH: "<<mlt_producer_get_playtime(m_mltProducer->get_producer());
500         return mlt_producer_get_playtime(m_mltProducer->get_producer());
501     }
502     return 0;
503 }
504
505 bool Render::isValid(KUrl url)
506 {
507     Mlt::Producer producer(*m_mltProfile, url.path().toUtf8().constData());
508     if (producer.is_blank())
509         return false;
510
511     return true;
512 }
513
514 double Render::dar() const
515 {
516     return m_mltProfile->dar();
517 }
518
519 double Render::sar() const
520 {
521     return m_mltProfile->sar();
522 }
523
524 void Render::slotSplitView(bool doit)
525 {
526     m_isSplitView = doit;
527     Mlt::Service service(m_mltProducer->parent().get_service());
528     Mlt::Tractor tractor(service);
529     if (service.type() != tractor_type || tractor.count() < 2) return;
530     Mlt::Field *field = tractor.field();
531     if (doit) {
532         for (int i = 1, screen = 0; i < tractor.count() && screen < 4; i++) {
533             Mlt::Producer trackProducer(tractor.track(i));
534             kDebug() << "// TRACK: " << i << ", HIDE: " << trackProducer.get("hide");
535             if (QString(trackProducer.get("hide")).toInt() != 1) {
536                 kDebug() << "// ADIDNG TRACK: " << i;
537                 Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
538                 transition->set("mlt_service", "composite");
539                 transition->set("a_track", 0);
540                 transition->set("b_track", i);
541                 transition->set("distort", 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
1709     /*mlt_image_format format = mlt_image_rgb24;
1710     int width = 0;
1711     int height = 0;
1712     const uchar* image = frame.get_image(format, width, height);
1713     QImage qimage(width, height, QImage::Format_RGB888);
1714     memcpy(qimage.bits(), image, width * height * 3);*/
1715     emit frameUpdated(qimage.rgbSwapped());
1716 }
1717
1718 void Render::emitFrameNumber()
1719 {
1720     int currentPos = m_mltConsumer->position();
1721     if (currentPos == requestedSeekPosition) requestedSeekPosition = SEEK_INACTIVE;
1722     emit rendererPosition(currentPos);
1723     if (requestedSeekPosition != SEEK_INACTIVE) {
1724         m_mltProducer->seek(requestedSeekPosition);
1725         requestedSeekPosition = SEEK_INACTIVE;
1726         if (m_mltProducer->get_speed() == 0) {
1727             refresh();
1728         }
1729     }
1730 }
1731
1732 void Render::emitConsumerStopped()
1733 {
1734     // This is used to know when the playing stopped
1735     if (m_mltProducer) {
1736         double pos = m_mltProducer->position();
1737         if (m_isLoopMode) play(m_loopStart);
1738         //else if (m_isZoneMode) resetZoneMode();
1739         emit rendererStopped((int) pos);
1740     }
1741 }
1742
1743 void Render::exportFileToFirewire(QString /*srcFileName*/, int /*port*/, GenTime /*startTime*/, GenTime /*endTime*/)
1744 {
1745     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1746 }
1747
1748 void Render::exportCurrentFrame(KUrl url, bool /*notify*/)
1749 {
1750     if (!m_mltProducer) {
1751         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1752         return;
1753     }
1754
1755     //int height = 1080;//KdenliveSettings::defaultheight();
1756     //int width = 1940; //KdenliveSettings::displaywidth();
1757     //TODO: rewrite
1758     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1759     /*
1760        QPixmap pix(width, height);
1761        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1762        m_convert.set("forced", mlt_image_rgb24a);
1763        m_mltProducer->attach(m_convert);
1764        Mlt::Frame * frame = m_mltProducer->get_frame();
1765        m_mltProducer->detach(m_convert);
1766        if (frame) {
1767            pix = frameThumbnail(frame, width, height);
1768            delete frame;
1769        }*/
1770     pix.save(url.path(), "PNG");
1771     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1772 }
1773
1774
1775 void Render::showFrame(Mlt::Frame& frame)
1776 {
1777     emit rendererPosition((int) m_mltConsumer->position());
1778     mlt_image_format format = mlt_image_rgb24a;
1779     int width = 0;
1780     int height = 0;
1781     const uchar* image = frame.get_image(format, width, height);
1782     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
1783     memcpy(qimage.scanLine(0), image, width * height * 4);
1784     emit showImageSignal(qimage);
1785     if (analyseAudio) showAudio(frame);
1786     if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
1787         emit frameUpdated(qimage.rgbSwapped());
1788     }
1789 }
1790
1791 void Render::disablePreview(bool disable)
1792 {
1793     if (m_mltConsumer) {
1794         m_mltConsumer->stop();
1795         m_mltConsumer->set("preview_off", (int) disable);
1796         m_mltConsumer->set("refresh", 0);
1797         m_mltConsumer->start();
1798     }
1799 }
1800
1801 void Render::showAudio(Mlt::Frame& frame)
1802 {
1803     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
1804         return;
1805     }
1806     mlt_audio_format audio_format = mlt_audio_s16;
1807     //FIXME: should not be hardcoded..
1808     int freq = 48000;
1809     int num_channels = 2;
1810     int samples = 0;
1811     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
1812
1813     if (!data) {
1814         return;
1815     }
1816
1817     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
1818     // So the vector is of size samples*channels.
1819     QVector<int16_t> sampleVector(samples*num_channels);
1820     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
1821
1822     if (samples > 0) {
1823         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
1824     }
1825 }
1826
1827 /*
1828  * MLT playlist direct manipulation.
1829  */
1830
1831 void Render::mltCheckLength(Mlt::Tractor *tractor)
1832 {
1833     //kDebug()<<"checking track length: "<<track<<"..........";
1834
1835     int trackNb = tractor->count();
1836     int duration = 0;
1837     int trackDuration;
1838     if (trackNb == 1) {
1839         Mlt::Producer trackProducer(tractor->track(0));
1840         duration = trackProducer.get_playtime() - 1;
1841         m_mltProducer->set("out", duration);
1842         emit durationChanged(duration);
1843         return;
1844     }
1845     while (trackNb > 1) {
1846         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
1847         trackDuration = trackProducer.get_playtime() - 1;
1848         // kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1849         if (trackDuration > duration) duration = trackDuration;
1850         trackNb--;
1851     }
1852
1853     Mlt::Producer blackTrackProducer(tractor->track(0));
1854
1855     if (blackTrackProducer.get_playtime() - 1 != duration) {
1856         Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1857         Mlt::Producer *blackclip = blackTrackPlaylist.get_clip(0);
1858         if (blackclip && blackclip->is_blank()) {
1859             delete blackclip;
1860             blackclip = NULL;
1861         }
1862
1863         if (blackclip == NULL || blackTrackPlaylist.count() != 1) {
1864             if (blackclip) delete blackclip;
1865             blackTrackPlaylist.clear();
1866             m_blackClip->set("length", duration + 1);
1867             m_blackClip->set("out", duration);
1868             blackclip = m_blackClip->cut(0, duration);
1869             blackTrackPlaylist.insert_at(0, blackclip, 1);
1870         } else {
1871             if (duration > blackclip->parent().get_length()) {
1872                 blackclip->parent().set("length", duration + 1);
1873                 blackclip->parent().set("out", duration);
1874                 blackclip->set("length", duration + 1);
1875             }
1876             blackTrackPlaylist.resize_clip(0, 0, duration);
1877         }
1878
1879         delete blackclip;
1880         m_mltProducer->set("out", duration);
1881         emit durationChanged(duration);
1882     }
1883 }
1884
1885 Mlt::Producer *Render::checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element)
1886 {
1887     if (element.attribute("speed", "1.0").toDouble() == 1.0 && element.attribute("strobe", "1").toInt() == 1) return prod;
1888     QLocale locale;
1889     // We want a slowmotion producer
1890     double speed = element.attribute("speed", "1.0").toDouble();
1891     int strobe = element.attribute("strobe", "1").toInt();
1892     QString url = QString::fromUtf8(prod->get("resource"));
1893     url.append('?' + locale.toString(speed));
1894     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
1895     Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1896     if (!slowprod || slowprod->get_producer() == NULL) {
1897         slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
1898         if (strobe > 1) slowprod->set("strobe", strobe);
1899         QString id = prod->parent().get("id");
1900         if (id.contains('_')) id = id.section('_', 0, 0);
1901         QString producerid = "slowmotion:" + id + ':' + locale.toString(speed);
1902         if (strobe > 1) producerid.append(':' + QString::number(strobe));
1903         slowprod->set("id", producerid.toUtf8().constData());
1904         m_slowmotionProducers.insert(url, slowprod);
1905     }
1906     return slowprod;
1907 }
1908
1909 int Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite, bool push)
1910 {
1911     if (m_mltProducer == NULL) {
1912         kDebug() << "PLAYLIST NOT INITIALISED //////";
1913         return -1;
1914     }
1915     if (prod == NULL) {
1916         kDebug() << "Cannot insert clip without producer //////";
1917         return -1;
1918     }
1919     Mlt::Producer parentProd(m_mltProducer->parent());
1920     if (parentProd.get_producer() == NULL) {
1921         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1922         return -1;
1923     }
1924
1925     Mlt::Service service(parentProd.get_service());
1926     if (service.type() != tractor_type) {
1927         kWarning() << "// TRACTOR PROBLEM";
1928         return -1;
1929     }
1930     Mlt::Tractor tractor(service);
1931     if (info.track > tractor.count() - 1) {
1932         kDebug() << "ERROR TRYING TO INSERT CLIP ON TRACK " << info.track << ", at POS: " << info.startPos.frames(25);
1933         return -1;
1934     }
1935     service.lock();
1936     Mlt::Producer trackProducer(tractor.track(info.track));
1937     int trackDuration = trackProducer.get_playtime() - 1;
1938     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1939     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
1940     prod = checkSlowMotionProducer(prod, element);
1941     if (prod == NULL || !prod->is_valid()) {
1942         service.unlock();
1943         return -1;
1944     }
1945
1946     int cutPos = (int) info.cropStart.frames(m_fps);
1947     if (cutPos < 0) cutPos = 0;
1948     int insertPos = (int) info.startPos.frames(m_fps);
1949     int cutDuration = (int)(info.endPos - info.startPos).frames(m_fps) - 1;
1950     Mlt::Producer *clip = prod->cut(cutPos, cutDuration + cutPos);
1951     if (overwrite && (insertPos < trackDuration)) {
1952         // Replace zone with blanks
1953         //trackPlaylist.split_at(insertPos, true);
1954         trackPlaylist.remove_region(insertPos, cutDuration + 1);
1955         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1956         trackPlaylist.insert_blank(clipIndex, cutDuration);
1957     } else if (push) {
1958         trackPlaylist.split_at(insertPos, true);
1959         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1960         trackPlaylist.insert_blank(clipIndex, cutDuration);
1961     }
1962     int newIndex = trackPlaylist.insert_at(insertPos, clip, 1);
1963     delete clip;
1964     /*if (QString(prod->get("transparency")).toInt() == 1)
1965         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
1966
1967     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength(&tractor);
1968     service.unlock();
1969     /*tractor.multitrack()->refresh();
1970     tractor.refresh();*/
1971     return 0;
1972 }
1973
1974
1975 bool Render::mltCutClip(int track, GenTime position)
1976 {
1977     Mlt::Service service(m_mltProducer->parent().get_service());
1978     if (service.type() != tractor_type) {
1979         kWarning() << "// TRACTOR PROBLEM";
1980         return false;
1981     }
1982
1983     Mlt::Tractor tractor(service);
1984     Mlt::Producer trackProducer(tractor.track(track));
1985     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1986
1987
1988     /* // Display playlist info
1989     kDebug()<<"////////////  BEFORE";
1990     for (int i = 0; i < trackPlaylist.count(); i++) {
1991     int blankStart = trackPlaylist.clip_start(i);
1992     int blankDuration = trackPlaylist.clip_length(i) - 1;
1993     QString blk;
1994     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1995     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
1996     }*/
1997
1998     int cutPos = (int) position.frames(m_fps);
1999
2000     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
2001     if (trackPlaylist.is_blank(clipIndex)) {
2002         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
2003         return false;
2004     }
2005     service.lock();
2006     int clipStart = trackPlaylist.clip_start(clipIndex);
2007     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
2008     service.unlock();
2009
2010     // duplicate effects
2011     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
2012     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
2013     
2014     if (original == NULL || clip == NULL) {
2015         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
2016         return false;
2017     }
2018
2019     Mlt::Service clipService(original->get_service());
2020     Mlt::Service dupService(clip->get_service());
2021
2022
2023     delete original;
2024     delete clip;
2025     int ct = 0;
2026     Mlt::Filter *filter = clipService.filter(ct);
2027     while (filter) {
2028         // Only duplicate Kdenlive filters, and skip the fade in effects
2029         if (filter->is_valid() && strcmp(filter->get("kdenlive_id"), "") && strcmp(filter->get("kdenlive_id"), "fadein") && strcmp(filter->get("kdenlive_id"), "fade_from_black")) {
2030             // looks like there is no easy way to duplicate a filter,
2031             // so we will create a new one and duplicate its properties
2032             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
2033             if (dup && dup->is_valid()) {
2034                 Mlt::Properties entries(filter->get_properties());
2035                 for (int i = 0; i < entries.count(); i++) {
2036                     dup->set(entries.get_name(i), entries.get(i));
2037                 }
2038                 dupService.attach(*dup);
2039             }
2040         }
2041         ct++;
2042         filter = clipService.filter(ct);
2043     }
2044     return true;
2045     /* // Display playlist info
2046     kDebug()<<"////////////  AFTER";
2047     for (int i = 0; i < trackPlaylist.count(); i++) {
2048     int blankStart = trackPlaylist.clip_start(i);
2049     int blankDuration = trackPlaylist.clip_length(i) - 1;
2050     QString blk;
2051     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2052     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2053     }*/
2054
2055 }
2056
2057 Mlt::Tractor *Render::lockService()
2058 {
2059     // we are going to replace some clips, purge consumer
2060     QMutexLocker locker(&m_mutex);
2061     if (!m_mltProducer) return NULL;
2062     if (m_mltConsumer) {
2063         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
2064         m_mltConsumer->purge();
2065     }
2066     Mlt::Service service(m_mltProducer->parent().get_service());
2067     if (service.type() != tractor_type) {
2068         kWarning() << "// TRACTOR PROBLEM";
2069         return NULL;
2070     }
2071     service.lock();
2072     return new Mlt::Tractor(service);
2073
2074 }
2075
2076 void Render::unlockService(Mlt::Tractor *tractor)
2077 {
2078     if (tractor) {
2079         delete tractor;
2080     }
2081     if (!m_mltProducer) return;
2082     Mlt::Service service(m_mltProducer->parent().get_service());
2083     if (service.type() != tractor_type) {
2084         kWarning() << "// TRACTOR PROBLEM";
2085         return;
2086     }
2087     service.unlock();
2088 }
2089
2090 bool Render::mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod)
2091 {
2092     // TODO: optimize
2093     if (prod == NULL || tractor == NULL) {
2094         kDebug() << "Cannot update clip with null producer //////";
2095         return false;
2096     }
2097
2098     Mlt::Producer trackProducer(tractor->track(tractor->count() - 1 - info.track));
2099     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2100     int startPos = info.startPos.frames(m_fps);
2101     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2102     if (trackPlaylist.is_blank(clipIndex)) {
2103         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << startPos;
2104         return false;
2105     }
2106     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2107     // keep effects
2108     QList <Mlt::Filter *> filtersList;
2109     Mlt::Service sourceService(clip->get_service());
2110     int ct = 0;
2111     Mlt::Filter *filter = sourceService.filter(ct);
2112     while (filter) {
2113         if (filter->get_int("kdenlive_ix") != 0) {
2114             filtersList.append(filter);
2115         }
2116         ct++;
2117         filter = sourceService.filter(ct);
2118     }
2119     delete clip;
2120     clip = trackPlaylist.replace_with_blank(clipIndex);
2121     delete clip;
2122     prod = checkSlowMotionProducer(prod, element);
2123     if (prod == NULL || !prod->is_valid()) {
2124         return false;
2125     }
2126
2127     Mlt::Producer *clip2 = prod->cut(info.cropStart.frames(m_fps), (info.cropDuration + info.cropStart).frames(m_fps) - 1);
2128     trackPlaylist.insert_at(info.startPos.frames(m_fps), clip2, 1);
2129     Mlt::Service destService(clip2->get_service());
2130     delete clip2;
2131
2132     if (!filtersList.isEmpty()) {
2133         for (int i = 0; i < filtersList.count(); i++)
2134             destService.attach(*(filtersList.at(i)));
2135     }
2136     return true;
2137 }
2138
2139
2140 bool Render::mltRemoveClip(int track, GenTime position)
2141 {
2142     Mlt::Service service(m_mltProducer->parent().get_service());
2143     if (service.type() != tractor_type) {
2144         kWarning() << "// TRACTOR PROBLEM";
2145         return false;
2146     }
2147     //service.lock();
2148     Mlt::Tractor tractor(service);
2149     Mlt::Producer trackProducer(tractor.track(track));
2150     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2151     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2152
2153     if (trackPlaylist.is_blank(clipIndex)) {
2154         kDebug() << "// WARNING, TRYING TO REMOVE A BLANK: " << position.frames(m_fps);
2155         //service.unlock();
2156         return false;
2157     }
2158     Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2159     if (clip) delete clip;
2160     trackPlaylist.consolidate_blanks(0);
2161
2162     /* // Display playlist info
2163     kDebug()<<"////  AFTER";
2164     for (int i = 0; i < trackPlaylist.count(); i++) {
2165     int blankStart = trackPlaylist.clip_start(i);
2166     int blankDuration = trackPlaylist.clip_length(i) - 1;
2167     QString blk;
2168     if (trackPlaylist.is_blank(i)) blk = "(blank)";
2169     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
2170     }*/
2171     //service.unlock();
2172     if (track != 0 && trackPlaylist.count() <= clipIndex) mltCheckLength(&tractor);
2173     return true;
2174 }
2175
2176 int Render::mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart)
2177 {
2178     if (!m_mltProducer) {
2179         kDebug() << "PLAYLIST NOT INITIALISED //////";
2180         return 0;
2181     }
2182     Mlt::Producer parentProd(m_mltProducer->parent());
2183     if (parentProd.get_producer() == NULL) {
2184         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2185         return 0;
2186     }
2187
2188     Mlt::Service service(parentProd.get_service());
2189     Mlt::Tractor tractor(service);
2190     int insertPos = pos.frames(m_fps);
2191
2192     Mlt::Producer trackProducer(tractor.track(track));
2193     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2194     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2195     if (clipIndex == trackPlaylist.count()) {
2196         // We are after the end of the playlist
2197         return -1;
2198     }
2199     if (!trackPlaylist.is_blank(clipIndex)) return 0;
2200     if (fromBlankStart) return trackPlaylist.clip_length(clipIndex);
2201     return trackPlaylist.clip_length(clipIndex) + trackPlaylist.clip_start(clipIndex) - insertPos;
2202 }
2203
2204 int Render::mltTrackDuration(int track)
2205 {
2206     if (!m_mltProducer) {
2207         kDebug() << "PLAYLIST NOT INITIALISED //////";
2208         return -1;
2209     }
2210     Mlt::Producer parentProd(m_mltProducer->parent());
2211     if (parentProd.get_producer() == NULL) {
2212         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2213         return -1;
2214     }
2215
2216     Mlt::Service service(parentProd.get_service());
2217     Mlt::Tractor tractor(service);
2218
2219     Mlt::Producer trackProducer(tractor.track(track));
2220     return trackProducer.get_playtime() - 1;
2221 }
2222
2223 void Render::mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset)
2224 {
2225     if (!m_mltProducer) {
2226         kDebug() << "PLAYLIST NOT INITIALISED //////";
2227         return;
2228     }
2229     Mlt::Producer parentProd(m_mltProducer->parent());
2230     if (parentProd.get_producer() == NULL) {
2231         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
2232         return;
2233     }
2234     //kDebug()<<"// CLP STRT LST: "<<trackClipStartList;
2235     //kDebug()<<"// TRA STRT LST: "<<trackTransitionStartList;
2236
2237     Mlt::Service service(parentProd.get_service());
2238     Mlt::Tractor tractor(service);
2239     service.lock();
2240     int diff = duration.frames(m_fps);
2241     int offset = timeOffset.frames(m_fps);
2242     int insertPos;
2243
2244     if (track != -1) {
2245         // insert space in one track only
2246         Mlt::Producer trackProducer(tractor.track(track));
2247         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2248         insertPos = trackClipStartList.value(track);
2249         if (insertPos != -1) {
2250             insertPos += offset;
2251             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2252             if (diff > 0) {
2253                 trackPlaylist.insert_blank(clipIndex, diff - 1);
2254             } else {
2255                 if (!trackPlaylist.is_blank(clipIndex)) clipIndex --;
2256                 if (!trackPlaylist.is_blank(clipIndex)) {
2257                     kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2258                 }
2259                 int position = trackPlaylist.clip_start(clipIndex);
2260                 int blankDuration = trackPlaylist.clip_length(clipIndex);
2261                 if (blankDuration + diff == 0) {
2262                     trackPlaylist.remove(clipIndex);
2263                 } else trackPlaylist.remove_region(position, -diff);
2264             }
2265             trackPlaylist.consolidate_blanks(0);
2266         }
2267         // now move transitions
2268         mlt_service serv = m_mltProducer->parent().get_service();
2269         mlt_service nextservice = mlt_service_get_producer(serv);
2270         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2271         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2272         QString resource = mlt_properties_get(properties, "mlt_service");
2273
2274         while (mlt_type == "transition") {
2275             mlt_transition tr = (mlt_transition) nextservice;
2276             int currentTrack = mlt_transition_get_b_track(tr);
2277             int currentIn = (int) mlt_transition_get_in(tr);
2278             int currentOut = (int) mlt_transition_get_out(tr);
2279             insertPos = trackTransitionStartList.value(track);
2280             if (insertPos != -1) {
2281                 insertPos += offset;
2282                 if (track == currentTrack && currentOut > insertPos && resource != "mix") {
2283                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2284                 }
2285             }
2286             nextservice = mlt_service_producer(nextservice);
2287             if (nextservice == NULL) break;
2288             properties = MLT_SERVICE_PROPERTIES(nextservice);
2289             mlt_type = mlt_properties_get(properties, "mlt_type");
2290             resource = mlt_properties_get(properties, "mlt_service");
2291         }
2292     } else {
2293         for (int trackNb = tractor.count() - 1; trackNb >= 1; --trackNb) {
2294             Mlt::Producer trackProducer(tractor.track(trackNb));
2295             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2296
2297             //int clipNb = trackPlaylist.count();
2298             insertPos = trackClipStartList.value(trackNb);
2299             if (insertPos != -1) {
2300                 insertPos += offset;
2301
2302                 /* kDebug()<<"-------------\nTRACK "<<trackNb<<" HAS "<<clipNb<<" CLPIS";
2303                  kDebug() << "INSERT SPACE AT: "<<insertPos<<", DIFF: "<<diff<<", TK: "<<trackNb;
2304                         for (int i = 0; i < clipNb; i++) {
2305                             kDebug()<<"CLIP "<<i<<", START: "<<trackPlaylist.clip_start(i)<<", END: "<<trackPlaylist.clip_start(i) + trackPlaylist.clip_length(i);
2306                      if (trackPlaylist.is_blank(i)) kDebug()<<"++ BLANK ++ ";
2307                      kDebug()<<"-------------";
2308                  }
2309                  kDebug()<<"END-------------";*/
2310
2311
2312                 int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
2313                 if (diff > 0) {
2314                     trackPlaylist.insert_blank(clipIndex, diff - 1);
2315                 } else {
2316                     if (!trackPlaylist.is_blank(clipIndex)) {
2317                         clipIndex --;
2318                     }
2319                     if (!trackPlaylist.is_blank(clipIndex)) {
2320                         kDebug() << "//// ERROR TRYING TO DELETE SPACE FROM " << insertPos;
2321                     }
2322                     int position = trackPlaylist.clip_start(clipIndex);
2323                     int blankDuration = trackPlaylist.clip_length(clipIndex);
2324                     if (diff + blankDuration == 0) {
2325                         trackPlaylist.remove(clipIndex);
2326                     } else trackPlaylist.remove_region(position, - diff);
2327                 }
2328                 trackPlaylist.consolidate_blanks(0);
2329             }
2330         }
2331         // now move transitions
2332         mlt_service serv = m_mltProducer->parent().get_service();
2333         mlt_service nextservice = mlt_service_get_producer(serv);
2334         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2335         QString mlt_type = mlt_properties_get(properties, "mlt_type");
2336         QString resource = mlt_properties_get(properties, "mlt_service");
2337
2338         while (mlt_type == "transition") {
2339             mlt_transition tr = (mlt_transition) nextservice;
2340             int currentIn = (int) mlt_transition_get_in(tr);
2341             int currentOut = (int) mlt_transition_get_out(tr);
2342             int currentTrack = mlt_transition_get_b_track(tr);
2343             insertPos = trackTransitionStartList.value(currentTrack);
2344             if (insertPos != -1) {
2345                 insertPos += offset;
2346                 if (currentOut > insertPos && resource != "mix") {
2347                     mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
2348                 }
2349             }
2350             nextservice = mlt_service_producer(nextservice);
2351             if (nextservice == NULL) break;
2352             properties = MLT_SERVICE_PROPERTIES(nextservice);
2353             mlt_type = mlt_properties_get(properties, "mlt_type");
2354             resource = mlt_properties_get(properties, "mlt_service");
2355         }
2356     }
2357     service.unlock();
2358     mltCheckLength(&tractor);
2359     m_mltConsumer->set("refresh", 1);
2360 }
2361
2362
2363 void Render::mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest)
2364 {
2365     if (source == dest) return;
2366     Mlt::Service sourceService(source->get_service());
2367     Mlt::Service destService(dest->get_service());
2368
2369     // move all effects to the correct producer
2370     int ct = 0;
2371     Mlt::Filter *filter = sourceService.filter(ct);
2372     while (filter) {
2373         if (filter->get_int("kdenlive_ix") != 0) {
2374             sourceService.detach(*filter);
2375             destService.attach(*filter);
2376         } else ct++;
2377         filter = sourceService.filter(ct);
2378     }
2379 }
2380
2381 int Render::mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double /*oldspeed*/, int strobe, Mlt::Producer *prod)
2382 {
2383     int newLength = 0;
2384     Mlt::Service service(m_mltProducer->parent().get_service());
2385     if (service.type() != tractor_type) {
2386         kWarning() << "// TRACTOR PROBLEM";
2387         return -1;
2388     }
2389
2390     //kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
2391     Mlt::Tractor tractor(service);
2392     Mlt::Producer trackProducer(tractor.track(info.track));
2393     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2394     int startPos = info.startPos.frames(m_fps);
2395     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
2396     int clipLength = trackPlaylist.clip_length(clipIndex);
2397
2398     Mlt::Producer *original = trackPlaylist.get_clip(clipIndex);
2399     if (original == NULL) {
2400         return -1;
2401     }
2402     if (!original->is_valid() || original->is_blank()) {
2403         // invalid clip
2404         delete original;
2405         return -1;
2406     }
2407     Mlt::Producer clipparent = original->parent();
2408     if (!clipparent.is_valid() || clipparent.is_blank()) {
2409         // invalid clip
2410         delete original;
2411         return -1;
2412     }
2413
2414     QString serv = clipparent.get("mlt_service");
2415     QString id = clipparent.get("id");
2416     if (speed <= 0 && speed > -1) speed = 1.0;
2417     //kDebug() << "CLIP SERVICE: " << serv;
2418     if ((serv == "avformat" || serv == "avformat-novalidate") && (speed != 1.0 || strobe > 1)) {
2419         service.lock();
2420         QString url = QString::fromUtf8(clipparent.get("resource"));
2421         url.append('?' + m_locale.toString(speed));
2422         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2423         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2424         if (!slowprod || slowprod->get_producer() == NULL) {
2425             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2426             if (strobe > 1) slowprod->set("strobe", strobe);
2427             QString producerid = "slowmotion:" + id + ':' + m_locale.toString(speed);
2428             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2429             slowprod->set("id", producerid.toUtf8().constData());
2430             // copy producer props
2431             double ar = original->parent().get_double("force_aspect_ratio");
2432             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2433             double fps = original->parent().get_double("force_fps");
2434             if (fps != 0.0) slowprod->set("force_fps", fps);
2435             int threads = original->parent().get_int("threads");
2436             if (threads != 0) slowprod->set("threads", threads);
2437             if (original->parent().get("force_progressive"))
2438                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2439             if (original->parent().get("force_tff"))
2440                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2441             int ix = original->parent().get_int("video_index");
2442             if (ix != 0) slowprod->set("video_index", ix);
2443             int colorspace = original->parent().get_int("force_colorspace");
2444             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2445             int full_luma = original->parent().get_int("set.force_full_luma");
2446             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2447             m_slowmotionProducers.insert(url, slowprod);
2448         }
2449         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2450         trackPlaylist.consolidate_blanks(0);
2451
2452         // Check that the blank space is long enough for our new duration
2453         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2454         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2455         Mlt::Producer *cut;
2456         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
2457             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2458             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
2459         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
2460
2461         // move all effects to the correct producer
2462         mltPasteEffects(clip, cut);
2463         trackPlaylist.insert_at(startPos, cut, 1);
2464         delete cut;
2465         delete clip;
2466         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2467         newLength = trackPlaylist.clip_length(clipIndex);
2468         service.unlock();
2469     } else if (speed == 1.0 && strobe < 2) {
2470         service.lock();
2471
2472         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2473         trackPlaylist.consolidate_blanks(0);
2474
2475         // Check that the blank space is long enough for our new duration
2476         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2477         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2478
2479         Mlt::Producer *cut;
2480         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps));
2481         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + speedIndependantInfo.cropDuration).frames(m_fps) > blankEnd) {
2482             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2483             cut = prod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2484         } else cut = prod->cut(originalStart, (int)(originalStart + speedIndependantInfo.cropDuration.frames(m_fps)) - 1);
2485
2486         // move all effects to the correct producer
2487         mltPasteEffects(clip, cut);
2488
2489         trackPlaylist.insert_at(startPos, cut, 1);
2490         delete cut;
2491         delete clip;
2492         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2493         newLength = trackPlaylist.clip_length(clipIndex);
2494         service.unlock();
2495
2496     } else if (serv == "framebuffer") {
2497         service.lock();
2498         QString url = QString::fromUtf8(clipparent.get("resource"));
2499         url = url.section('?', 0, 0);
2500         url.append('?' + m_locale.toString(speed));
2501         if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
2502         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
2503         if (!slowprod || slowprod->get_producer() == NULL) {
2504             slowprod = new Mlt::Producer(*m_mltProfile, 0, ("framebuffer:" + url).toUtf8().constData());
2505             slowprod->set("strobe", strobe);
2506             QString producerid = "slowmotion:" + id.section(':', 1, 1) + ':' + m_locale.toString(speed);
2507             if (strobe > 1) producerid.append(':' + QString::number(strobe));
2508             slowprod->set("id", producerid.toUtf8().constData());
2509             // copy producer props
2510             double ar = original->parent().get_double("force_aspect_ratio");
2511             if (ar != 0.0) slowprod->set("force_aspect_ratio", ar);
2512             double fps = original->parent().get_double("force_fps");
2513             if (fps != 0.0) slowprod->set("force_fps", fps);
2514             if (original->parent().get("force_progressive"))
2515                 slowprod->set("force_progressive", original->parent().get_int("force_progressive"));
2516             if (original->parent().get("force_tff"))
2517                 slowprod->set("force_tff", original->parent().get_int("force_tff"));
2518             int threads = original->parent().get_int("threads");
2519             if (threads != 0) slowprod->set("threads", threads);
2520             int ix = original->parent().get_int("video_index");
2521             if (ix != 0) slowprod->set("video_index", ix);
2522             int colorspace = original->parent().get_int("force_colorspace");
2523             if (colorspace != 0) slowprod->set("force_colorspace", colorspace);
2524             int full_luma = original->parent().get_int("set.force_full_luma");
2525             if (full_luma != 0) slowprod->set("set.force_full_luma", full_luma);
2526             m_slowmotionProducers.insert(url, slowprod);
2527         }
2528         Mlt::Producer *clip = trackPlaylist.replace_with_blank(clipIndex);
2529         trackPlaylist.consolidate_blanks(0);
2530
2531         GenTime duration = speedIndependantInfo.cropDuration / speed;
2532         int originalStart = (int)(speedIndependantInfo.cropStart.frames(m_fps) / speed);
2533
2534         // Check that the blank space is long enough for our new duration
2535         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2536         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
2537
2538         Mlt::Producer *cut;
2539         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + duration).frames(m_fps) > blankEnd) {
2540             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
2541             cut = slowprod->cut(originalStart, (int)(originalStart + maxLength.frames(m_fps) - 1));
2542         } else cut = slowprod->cut(originalStart, (int)(originalStart + duration.frames(m_fps)) - 1);
2543
2544         // move all effects to the correct producer
2545         mltPasteEffects(clip, cut);
2546
2547         trackPlaylist.insert_at(startPos, cut, 1);
2548         delete cut;
2549         delete clip;
2550         clipIndex = trackPlaylist.get_clip_index_at(startPos);
2551         newLength = trackPlaylist.clip_length(clipIndex);
2552
2553         service.unlock();
2554     }
2555     delete original;
2556     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength(&tractor);
2557     return newLength;
2558 }
2559
2560 bool Render::mltRemoveTrackEffect(int track, int index, bool updateIndex)
2561 {
2562     Mlt::Service service(m_mltProducer->parent().get_service());
2563     bool success = false;
2564     Mlt::Tractor tractor(service);
2565     Mlt::Producer trackProducer(tractor.track(track));
2566     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2567     Mlt::Service clipService(trackPlaylist.get_service());
2568
2569     service.lock();
2570     int ct = 0;
2571     Mlt::Filter *filter = clipService.filter(ct);
2572     while (filter) {
2573         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {
2574             if (clipService.detach(*filter) == 0) success = true;
2575         } else if (updateIndex) {
2576             // Adjust the other effects index
2577             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2578             ct++;
2579         } else ct++;
2580         filter = clipService.filter(ct);
2581     }
2582     service.unlock();
2583     refresh();
2584     return success;
2585 }
2586
2587 bool Render::mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh)
2588 {
2589     if (position < GenTime()) {
2590         // Remove track effect
2591         return mltRemoveTrackEffect(track, index, updateIndex);
2592     }
2593     Mlt::Service service(m_mltProducer->parent().get_service());
2594     bool success = false;
2595     Mlt::Tractor tractor(service);
2596     Mlt::Producer trackProducer(tractor.track(track));
2597     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2598
2599     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2600     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2601     if (!clip) {
2602         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
2603         return false;
2604     }
2605
2606     Mlt::Service clipService(clip->get_service());
2607     int duration = clip->get_playtime();
2608     if (doRefresh) {
2609         // Check if clip is visible in monitor
2610         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2611         if (diff < 0 || diff > duration) doRefresh = false;
2612     }
2613     delete clip;
2614
2615     service.lock();
2616     int ct = 0;
2617     Mlt::Filter *filter = clipService.filter(ct);
2618     while (filter) {
2619         if ((index == -1 && strcmp(filter->get("kdenlive_id"), ""))  || filter->get_int("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
2620             if (clipService.detach(*filter) == 0) success = true;
2621             //kDebug()<<"Deleted filter id:"<<filter->get("kdenlive_id")<<", ix:"<<filter->get("kdenlive_ix")<<", SERVICE:"<<filter->get("mlt_service");
2622         } else if (updateIndex) {
2623             // Adjust the other effects index
2624             if (filter->get_int("kdenlive_ix") > index) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
2625             ct++;
2626         } else ct++;
2627         filter = clipService.filter(ct);
2628     }
2629     service.unlock();
2630     if (doRefresh) refresh();
2631     return success;
2632 }
2633
2634 bool Render::mltAddTrackEffect(int track, EffectsParameterList params)
2635 {
2636     Mlt::Service service(m_mltProducer->parent().get_service());
2637     Mlt::Tractor tractor(service);
2638     Mlt::Producer trackProducer(tractor.track(track));
2639     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2640     Mlt::Service trackService(trackProducer.get_service()); //trackPlaylist
2641     return mltAddEffect(trackService, params, trackProducer.get_playtime() - 1, true);
2642 }
2643
2644
2645 bool Render::mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh)
2646 {
2647
2648     Mlt::Service service(m_mltProducer->parent().get_service());
2649
2650     Mlt::Tractor tractor(service);
2651     Mlt::Producer trackProducer(tractor.track(track));
2652     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2653
2654     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2655     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2656     if (!clip) {
2657         return false;
2658     }
2659
2660     Mlt::Service clipService(clip->get_service());
2661     int duration = clip->get_playtime();
2662     if (doRefresh) {
2663         // Check if clip is visible in monitor
2664         int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2665         if (diff < 0 || diff > duration) doRefresh = false;
2666     }
2667     delete clip;
2668     return mltAddEffect(clipService, params, duration, doRefresh);
2669 }
2670
2671 bool Render::mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh)
2672 {
2673     bool updateIndex = false;
2674     const int filter_ix = params.paramValue("kdenlive_ix").toInt();
2675     int ct = 0;
2676     service.lock();
2677
2678     Mlt::Filter *filter = service.filter(ct);
2679     while (filter) {
2680         if (filter->get_int("kdenlive_ix") == filter_ix) {
2681             // A filter at that position already existed, so we will increase all indexes later
2682             updateIndex = true;
2683             break;
2684         }
2685         ct++;
2686         filter = service.filter(ct);
2687     }
2688
2689     if (params.paramValue("id") == "speed") {
2690         // special case, speed effect is not really inserted, we just update the other effects index (kdenlive_ix)
2691         ct = 0;
2692         filter = service.filter(ct);
2693         while (filter) {
2694             if (filter->get_int("kdenlive_ix") >= filter_ix) {
2695                 if (updateIndex) filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2696             }
2697             ct++;
2698             filter = service.filter(ct);
2699         }
2700         service.unlock();
2701         if (doRefresh) refresh();
2702         return true;
2703     }
2704
2705
2706     // temporarily remove all effects after insert point
2707     QList <Mlt::Filter *> filtersList;
2708     ct = 0;
2709     filter = service.filter(ct);
2710     while (filter) {
2711         if (filter->get_int("kdenlive_ix") >= filter_ix) {
2712             filtersList.append(filter);
2713             service.detach(*filter);
2714         } else ct++;
2715         filter = service.filter(ct);
2716     }
2717
2718     addFilterToService(service, params, duration);
2719
2720     // re-add following filters
2721     for (int i = 0; i < filtersList.count(); i++) {
2722         Mlt::Filter *filter = filtersList.at(i);
2723         if (updateIndex)
2724             filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") + 1);
2725         service.attach(*filter);
2726     }
2727     service.unlock();
2728     if (doRefresh) refresh();
2729     return true;
2730 }
2731
2732
2733 bool Render::addFilterToService(Mlt::Service service, EffectsParameterList params, int duration)
2734 {
2735       // create filter
2736     QString tag =  params.paramValue("tag");
2737     //kDebug() << " / / INSERTING EFFECT: " << tag << ", REGI: " << region;
2738     char *filterTag = qstrdup(tag.toUtf8().constData());
2739     char *filterId = qstrdup(params.paramValue("id").toUtf8().constData());
2740     QString kfr = params.paramValue("keyframes");
2741   if (!kfr.isEmpty()) {
2742         QStringList keyFrames = kfr.split(';', QString::SkipEmptyParts);
2743         //kDebug() << "// ADDING KEYFRAME EFFECT: " << params.paramValue("keyframes");
2744         char *starttag = qstrdup(params.paramValue("starttag", "start").toUtf8().constData());
2745         char *endtag = qstrdup(params.paramValue("endtag", "end").toUtf8().constData());
2746         //kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
2747         //double max = params.paramValue("max").toDouble();
2748         double min = params.paramValue("min").toDouble();
2749         double factor = params.paramValue("factor", "1").toDouble();
2750         double paramOffset = params.paramValue("offset", "0").toDouble();
2751         params.removeParam("starttag");
2752         params.removeParam("endtag");
2753         params.removeParam("keyframes");
2754         params.removeParam("min");
2755         params.removeParam("max");
2756         params.removeParam("factor");
2757         params.removeParam("offset");
2758         int offset = 0;
2759         // Special case, only one keyframe, means we want a constant value
2760         if (keyFrames.count() == 1) {
2761             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2762             if (filter && filter->is_valid()) {
2763                 filter->set("kdenlive_id", filterId);
2764                 int x1 = keyFrames.at(0).section(':', 0, 0).toInt();
2765                 double y1 = keyFrames.at(0).section(':', 1, 1).toDouble();
2766                 for (int j = 0; j < params.count(); j++) {
2767                     filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2768                 }
2769                 filter->set("in", x1);
2770                 //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2771                 filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2772                 service.attach(*filter);
2773             }
2774         } else for (int i = 0; i < keyFrames.size() - 1; ++i) {
2775                 Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
2776                 if (filter && filter->is_valid()) {
2777                     filter->set("kdenlive_id", filterId);
2778                     int x1 = keyFrames.at(i).section(':', 0, 0).toInt() + offset;
2779                     double y1 = keyFrames.at(i).section(':', 1, 1).toDouble();
2780                     int x2 = keyFrames.at(i + 1).section(':', 0, 0).toInt();
2781                     double y2 = keyFrames.at(i + 1).section(':', 1, 1).toDouble();
2782                     if (x2 == -1) x2 = duration;
2783
2784                     for (int j = 0; j < params.count(); j++) {
2785                         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2786                     }
2787
2788                     filter->set("in", x1);
2789                     filter->set("out", x2);
2790                     //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
2791                     filter->set(starttag, m_locale.toString(((min + y1) - paramOffset) / factor).toUtf8().data());
2792                     filter->set(endtag, m_locale.toString(((min + y2) - paramOffset) / factor).toUtf8().data());
2793                     service.attach(*filter);
2794                     offset = 1;
2795                 }
2796             }
2797         delete[] starttag;
2798         delete[] endtag;
2799     } else {
2800         Mlt::Filter *filter;
2801         QString prefix;
2802         filter = new Mlt::Filter(*m_mltProfile, filterTag);
2803         if (filter && filter->is_valid()) {
2804             filter->set("kdenlive_id", filterId);
2805         } else {
2806             kDebug() << "filter is NULL";
2807             service.unlock();
2808             return false;
2809         }
2810         params.removeParam("kdenlive_id");
2811         if (params.hasParam("_sync_in_out")) {
2812             // This effect must sync in / out with parent clip
2813             params.removeParam("_sync_in_out");
2814             filter->set_in_and_out(service.get_int("in"), service.get_int("out"));
2815         }
2816
2817         for (int j = 0; j < params.count(); j++) {
2818             filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2819         }
2820
2821         if (tag == "sox") {
2822             QString effectArgs = params.paramValue("id").section('_', 1);
2823
2824             params.removeParam("id");
2825             params.removeParam("kdenlive_ix");
2826             params.removeParam("tag");
2827             params.removeParam("disable");
2828             params.removeParam("region");
2829
2830             for (int j = 0; j < params.count(); j++) {
2831                 effectArgs.append(' ' + params.at(j).value());
2832             }
2833             //kDebug() << "SOX EFFECTS: " << effectArgs.simplified();
2834             filter->set("effect", effectArgs.simplified().toUtf8().constData());
2835         }
2836         // attach filter to the clip
2837         service.attach(*filter);
2838     }
2839         
2840     delete[] filterId;
2841     delete[] filterTag;
2842     return true;
2843 }
2844
2845 bool Render::mltEditTrackEffect(int track, EffectsParameterList params)
2846 {
2847     Mlt::Service service(m_mltProducer->parent().get_service());
2848     Mlt::Tractor tractor(service);
2849     Mlt::Producer trackProducer(tractor.track(track));
2850     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2851     Mlt::Service clipService(trackPlaylist.get_service());
2852     int ct = 0;
2853     QString index = params.paramValue("kdenlive_ix");
2854     QString tag =  params.paramValue("tag");
2855
2856     Mlt::Filter *filter = clipService.filter(ct);
2857     while (filter) {
2858         if (filter->get_int("kdenlive_ix") == index.toInt()) {
2859             break;
2860         }
2861         ct++;
2862         filter = clipService.filter(ct);
2863     }
2864
2865     if (!filter) {
2866         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2867         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2868
2869         bool success = false;//mltAddTrackEffect(track, params);
2870         return success;
2871     }
2872     QString prefix;
2873     QString ser = filter->get("mlt_service");
2874     if (ser == "region") prefix = "filter0.";
2875     service.lock();
2876     for (int j = 0; j < params.count(); j++) {
2877         filter->set((prefix + params.at(j).name()).toUtf8().constData(), params.at(j).value().toUtf8().constData());
2878     }
2879     service.unlock();
2880
2881     refresh();
2882     return true;
2883 }
2884
2885 bool Render::mltEditEffect(int track, GenTime position, EffectsParameterList params)
2886 {
2887     int index = params.paramValue("kdenlive_ix").toInt();
2888     QString tag =  params.paramValue("tag");
2889
2890     if (!params.paramValue("keyframes").isEmpty() || (tag == "affine" && params.hasParam("background")) || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
2891         // This is a keyframe effect, to edit it, we remove it and re-add it.
2892         bool success = mltRemoveEffect(track, position, index, false);
2893 //         if (!success) kDebug() << "// ERROR Removing effect : " << index;
2894         if (position < GenTime())
2895             success = mltAddTrackEffect(track, params);
2896         else
2897             success = mltAddEffect(track, position, params);
2898 //         if (!success) kDebug() << "// ERROR Adding effect : " << index;
2899         return success;
2900     }
2901     if (position < GenTime()) {
2902         return mltEditTrackEffect(track, params);
2903     }
2904     // find filter
2905     Mlt::Service service(m_mltProducer->parent().get_service());
2906     Mlt::Tractor tractor(service);
2907     Mlt::Producer trackProducer(tractor.track(track));
2908     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2909
2910     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
2911     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2912     if (!clip) {
2913         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
2914         return false;
2915     }
2916
2917     int duration = clip->get_playtime();
2918     bool doRefresh = true;
2919     // Check if clip is visible in monitor
2920     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
2921     if (diff < 0 || diff > duration)
2922         doRefresh = false;
2923     int ct = 0;
2924
2925     Mlt::Filter *filter = clip->filter(ct);
2926     while (filter) {
2927         if (filter->get_int("kdenlive_ix") == index) {
2928             break;
2929         }
2930         ct++;
2931         filter = clip->filter(ct);
2932     }
2933
2934     if (!filter) {
2935         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT! " << index << ", " << tag;
2936         // filter was not found, it was probably a disabled filter, so add it to the correct place...
2937
2938         bool success = mltAddEffect(track, position, params);
2939         return success;
2940     }
2941     ct = 0;
2942     QString ser = filter->get("mlt_service");
2943     QList <Mlt::Filter *> filtersList;
2944     service.lock();
2945     if (ser != tag) {
2946         // Effect service changes, delete effect and re-add it
2947         clip->detach(*filter);  
2948         
2949         // Delete all effects after deleted one
2950         filter = clip->filter(ct);
2951         while (filter) {
2952             if (filter->get_int("kdenlive_ix") > index) {
2953                 filtersList.append(filter);
2954                 clip->detach(*filter);
2955             }
2956             else ct++;
2957             filter = clip->filter(ct);
2958         }
2959         
2960         // re-add filter
2961         addFilterToService(*clip, params, clip->get_playtime());
2962         delete clip;
2963         service.unlock();
2964
2965         if (doRefresh) refresh();
2966         return true;
2967     }
2968     if (params.hasParam("_sync_in_out")) {
2969         // This effect must sync in / out with parent clip
2970         params.removeParam("_sync_in_out");
2971         filter->set_in_and_out(clip->get_in(), clip->get_out());
2972     }
2973
2974     for (int j = 0; j < params.count(); j++) {
2975         filter->set(params.at(j).name().toUtf8().constData(), params.at(j).value().toUtf8().constData());
2976     }
2977     
2978     for (int j = 0; j < filtersList.count(); j++) {
2979         clip->attach(*(filtersList.at(j)));
2980     }
2981
2982     delete clip;
2983     service.unlock();
2984
2985     if (doRefresh) refresh();
2986     return true;
2987 }
2988
2989 bool Render::mltEnableEffects(int track, GenTime position, QList <int> effectIndexes, bool disable)
2990 {
2991     if (position < GenTime()) {
2992         return mltEnableTrackEffects(track, effectIndexes, disable);
2993     }
2994     // find filter
2995     Mlt::Service service(m_mltProducer->parent().get_service());
2996     Mlt::Tractor tractor(service);
2997     Mlt::Producer trackProducer(tractor.track(track));
2998     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2999
3000     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3001     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3002     if (!clip) {
3003         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3004         return false;
3005     }
3006
3007     int duration = clip->get_playtime();
3008     bool doRefresh = true;
3009     // Check if clip is visible in monitor
3010     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3011     if (diff < 0 || diff > duration)
3012         doRefresh = false;
3013     int ct = 0;
3014
3015     Mlt::Filter *filter = clip->filter(ct);
3016     while (filter) {
3017         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3018             filter->set("disable", (int) disable);
3019         }
3020         ct++;
3021         filter = clip->filter(ct);
3022     }
3023
3024     delete clip;
3025     service.unlock();
3026
3027     if (doRefresh) refresh();
3028     return true;
3029 }
3030
3031 bool Render::mltEnableTrackEffects(int track, QList <int> effectIndexes, bool disable)
3032 {
3033     Mlt::Service service(m_mltProducer->parent().get_service());
3034     Mlt::Tractor tractor(service);
3035     Mlt::Producer trackProducer(tractor.track(track));
3036     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3037     Mlt::Service clipService(trackPlaylist.get_service());
3038     int ct = 0;
3039
3040     Mlt::Filter *filter = clipService.filter(ct);
3041     while (filter) {
3042         if (effectIndexes.contains(filter->get_int("kdenlive_ix"))) {
3043             filter->set("disable", (int) disable);
3044         }
3045         ct++;
3046         filter = clipService.filter(ct);
3047     }
3048     service.unlock();
3049
3050     refresh();
3051     return true;
3052 }
3053
3054 void Render::mltUpdateEffectPosition(int track, GenTime position, int oldPos, int newPos)
3055 {
3056     Mlt::Service service(m_mltProducer->parent().get_service());
3057     Mlt::Tractor tractor(service);
3058     Mlt::Producer trackProducer(tractor.track(track));
3059     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3060
3061     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3062     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3063     if (!clip) {
3064         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3065         return;
3066     }
3067
3068     Mlt::Service clipService(clip->get_service());
3069     int duration = clip->get_playtime();
3070     bool doRefresh = true;
3071     // Check if clip is visible in monitor
3072     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3073     if (diff < 0 || diff > duration) doRefresh = false;
3074     delete clip;
3075
3076     int ct = 0;
3077     Mlt::Filter *filter = clipService.filter(ct);
3078     while (filter) {
3079         int pos = filter->get_int("kdenlive_ix");
3080         if (pos == oldPos) {
3081             filter->set("kdenlive_ix", newPos);
3082         } else ct++;
3083         filter = clipService.filter(ct);
3084     }
3085     if (doRefresh) refresh();
3086 }
3087
3088 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos)
3089 {
3090     if (position < GenTime()) {
3091         mltMoveTrackEffect(track, oldPos, newPos);
3092         return;
3093     }
3094     Mlt::Service service(m_mltProducer->parent().get_service());
3095     Mlt::Tractor tractor(service);
3096     Mlt::Producer trackProducer(tractor.track(track));
3097     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3098
3099     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
3100     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3101     if (!clip) {
3102         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
3103         return;
3104     }
3105
3106     Mlt::Service clipService(clip->get_service());
3107     int duration = clip->get_playtime();
3108     bool doRefresh = true;
3109     // Check if clip is visible in monitor
3110     int diff = trackPlaylist.clip_start(clipIndex) + duration - m_mltProducer->position();
3111     if (diff < 0 || diff > duration) doRefresh = false;
3112     delete clip;
3113
3114     int ct = 0;
3115     QList <Mlt::Filter *> filtersList;
3116     Mlt::Filter *filter = clipService.filter(ct);
3117     bool found = false;
3118     if (newPos > oldPos) {
3119         while (filter) {
3120             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3121                 filter->set("kdenlive_ix", newPos);
3122                 filtersList.append(filter);
3123                 clipService.detach(*filter);
3124                 filter = clipService.filter(ct);
3125                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3126                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3127                     ct++;
3128                     filter = clipService.filter(ct);
3129                 }
3130                 found = true;
3131             }
3132             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3133                 filtersList.append(filter);
3134                 clipService.detach(*filter);
3135             } else ct++;
3136             filter = clipService.filter(ct);
3137         }
3138     } else {
3139         while (filter) {
3140             if (filter->get_int("kdenlive_ix") == oldPos) {
3141                 filter->set("kdenlive_ix", newPos);
3142                 filtersList.append(filter);
3143                 clipService.detach(*filter);
3144             } else ct++;
3145             filter = clipService.filter(ct);
3146         }
3147
3148         ct = 0;
3149         filter = clipService.filter(ct);
3150         while (filter) {
3151             int pos = filter->get_int("kdenlive_ix");
3152             if (pos >= newPos) {
3153                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3154                 filtersList.append(filter);
3155                 clipService.detach(*filter);
3156             } else ct++;
3157             filter = clipService.filter(ct);
3158         }
3159     }
3160
3161     for (int i = 0; i < filtersList.count(); i++) {
3162         clipService.attach(*(filtersList.at(i)));
3163     }
3164
3165     if (doRefresh) refresh();
3166 }
3167
3168 void Render::mltMoveTrackEffect(int track, int oldPos, int newPos)
3169 {
3170     Mlt::Service service(m_mltProducer->parent().get_service());
3171     Mlt::Tractor tractor(service);
3172     Mlt::Producer trackProducer(tractor.track(track));
3173     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3174     Mlt::Service clipService(trackPlaylist.get_service());
3175     int ct = 0;
3176     QList <Mlt::Filter *> filtersList;
3177     Mlt::Filter *filter = clipService.filter(ct);
3178     bool found = false;
3179     if (newPos > oldPos) {
3180         while (filter) {
3181             if (!found && filter->get_int("kdenlive_ix") == oldPos) {
3182                 filter->set("kdenlive_ix", newPos);
3183                 filtersList.append(filter);
3184                 clipService.detach(*filter);
3185                 filter = clipService.filter(ct);
3186                 while (filter && filter->get_int("kdenlive_ix") <= newPos) {
3187                     filter->set("kdenlive_ix", filter->get_int("kdenlive_ix") - 1);
3188                     ct++;
3189                     filter = clipService.filter(ct);
3190                 }
3191                 found = true;
3192             }
3193             if (filter && filter->get_int("kdenlive_ix") > newPos) {
3194                 filtersList.append(filter);
3195                 clipService.detach(*filter);
3196             } else ct++;
3197             filter = clipService.filter(ct);
3198         }
3199     } else {
3200         while (filter) {
3201             if (filter->get_int("kdenlive_ix") == oldPos) {
3202                 filter->set("kdenlive_ix", newPos);
3203                 filtersList.append(filter);
3204                 clipService.detach(*filter);
3205             } else ct++;
3206             filter = clipService.filter(ct);
3207         }
3208
3209         ct = 0;
3210         filter = clipService.filter(ct);
3211         while (filter) {
3212             int pos = filter->get_int("kdenlive_ix");
3213             if (pos >= newPos) {
3214                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
3215                 filtersList.append(filter);
3216                 clipService.detach(*filter);
3217             } else ct++;
3218             filter = clipService.filter(ct);
3219         }
3220     }
3221
3222     for (int i = 0; i < filtersList.count(); i++) {
3223         clipService.attach(*(filtersList.at(i)));
3224     }
3225     refresh();
3226 }
3227
3228 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration)
3229 {
3230     Mlt::Service service(m_mltProducer->parent().get_service());
3231     Mlt::Tractor tractor(service);
3232     Mlt::Producer trackProducer(tractor.track(info.track));
3233     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3234
3235     /* // Display playlist info
3236     kDebug()<<"////////////  BEFORE RESIZE";
3237     for (int i = 0; i < trackPlaylist.count(); i++) {
3238     int blankStart = trackPlaylist.clip_start(i);
3239     int blankDuration = trackPlaylist.clip_length(i) - 1;
3240     QString blk;
3241     if (trackPlaylist.is_blank(i)) blk = "(blank)";
3242     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<'x'<<blankStart + blankDuration<<")"<<blk;
3243     }*/
3244
3245     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
3246         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3247         return false;
3248     }
3249     service.lock();
3250     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
3251     //kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
3252     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3253
3254     int previousStart = clip->get_in();
3255     int newDuration = (int) clipDuration.frames(m_fps) - 1;
3256     int diff = newDuration - (trackPlaylist.clip_length(clipIndex) - 1);
3257
3258     int currentOut = newDuration + previousStart;
3259     if (currentOut > clip->get_length()) {
3260         clip->parent().set("length", currentOut + 1);
3261         clip->parent().set("out", currentOut);
3262         clip->set("length", currentOut + 1);
3263     }
3264
3265     /*if (newDuration > clip->get_out()) {
3266         clip->parent().set_in_and_out(0, newDuration + 1);
3267         clip->set_in_and_out(0, newDuration + 1);
3268     }*/
3269     delete clip;
3270     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
3271     trackPlaylist.consolidate_blanks(0);
3272     // skip to next clip
3273     clipIndex++;
3274     //kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration << ", IX: " << clipIndex << ", MAX: " << trackPlaylist.count();
3275     if (diff > 0) {
3276         // clip was made longer, trim next blank if there is one.
3277         if (clipIndex < trackPlaylist.count()) {
3278             // If this is not the last clip in playlist
3279             if (trackPlaylist.is_blank(clipIndex)) {
3280                 int blankStart = trackPlaylist.clip_start(clipIndex);
3281                 int blankDuration = trackPlaylist.clip_length(clipIndex);
3282                 if (diff > blankDuration) {
3283                     kDebug() << "// ERROR blank clip is not large enough to get back required space!!!";
3284                 }
3285                 if (diff - blankDuration == 0) {
3286                     trackPlaylist.remove(clipIndex);
3287                 } else trackPlaylist.remove_region(blankStart, diff);
3288             } else {
3289                 kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
3290             }
3291         }
3292     } else if (clipIndex != trackPlaylist.count()) trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
3293     trackPlaylist.consolidate_blanks(0);
3294     service.unlock();
3295
3296     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength(&tractor);
3297     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3298         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
3299         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3300         ItemInfo transpinfo;
3301         transpinfo.startPos = info.startPos;
3302         transpinfo.endPos = info.startPos + clipDuration;
3303         transpinfo.track = info.track;
3304         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3305     }*/
3306     m_mltConsumer->set("refresh", 1);
3307     return true;
3308 }
3309
3310 void Render::mltChangeTrackState(int track, bool mute, bool blind)
3311 {
3312     Mlt::Service service(m_mltProducer->parent().get_service());
3313     Mlt::Tractor tractor(service);
3314     Mlt::Producer trackProducer(tractor.track(track));
3315
3316     // Make sure muting will not produce problems with our audio mixing transition,
3317     // because audio mixing is done between each track and the lowest one
3318     bool audioMixingBroken = false;
3319     if (mute && trackProducer.get_int("hide") < 2 ) {
3320             // We mute a track with sound
3321             if (track == getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3322             kDebug()<<"Muting track: "<<track <<" / "<<getLowestNonMutedAudioTrack(tractor);
3323     }
3324     else if (!mute && trackProducer.get_int("hide") > 1 ) {
3325             // We un-mute a previously muted track
3326             if (track < getLowestNonMutedAudioTrack(tractor)) audioMixingBroken = true;
3327     }
3328
3329     if (mute) {
3330         if (blind) trackProducer.set("hide", 3);
3331         else trackProducer.set("hide", 2);
3332     } else if (blind) {
3333         trackProducer.set("hide", 1);
3334     } else {
3335         trackProducer.set("hide", 0);
3336     }
3337     if (audioMixingBroken) fixAudioMixing(tractor);
3338
3339     tractor.multitrack()->refresh();
3340     tractor.refresh();
3341     refresh();
3342 }
3343
3344 int Render::getLowestNonMutedAudioTrack(Mlt::Tractor tractor)
3345 {
3346     for (int i = 1; i < tractor.count(); i++) {
3347         Mlt::Producer trackProducer(tractor.track(i));
3348         if (trackProducer.get_int("hide") < 2) return i;
3349     }
3350     return tractor.count() - 1;
3351 }
3352
3353 void Render::fixAudioMixing(Mlt::Tractor tractor)
3354 {
3355     // Make sure the audio mixing transitions are applied to the lowest audible (non muted) track
3356     int lowestTrack = getLowestNonMutedAudioTrack(tractor);
3357
3358     mlt_service serv = m_mltProducer->parent().get_service();
3359     Mlt::Field *field = tractor.field();
3360     mlt_service_lock(serv);
3361
3362     mlt_service nextservice = mlt_service_get_producer(serv);
3363     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3364     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3365     QString resource = mlt_properties_get(properties, "mlt_service");
3366
3367     mlt_service nextservicetodisconnect;
3368      // Delete all audio mixing transitions
3369     while (mlt_type == "transition") {
3370         if (resource == "mix") {
3371             nextservicetodisconnect = nextservice;
3372             nextservice = mlt_service_producer(nextservice);
3373             mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
3374         }
3375         else nextservice = mlt_service_producer(nextservice);
3376         if (nextservice == NULL) break;
3377         properties = MLT_SERVICE_PROPERTIES(nextservice);
3378         mlt_type = mlt_properties_get(properties, "mlt_type");
3379         resource = mlt_properties_get(properties, "mlt_service");
3380     }
3381
3382     // Re-add correct audio transitions
3383     for (int i = lowestTrack + 1; i < tractor.count(); i++) {
3384         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "mix");
3385         transition->set("always_active", 1);
3386         transition->set("combine", 1);
3387         transition->set("internal_added", 237);
3388         field->plant_transition(*transition, lowestTrack, i);
3389     }
3390     mlt_service_unlock(serv);
3391 }
3392
3393 bool Render::mltResizeClipCrop(ItemInfo info, GenTime newCropStart)
3394 {
3395     Mlt::Service service(m_mltProducer->parent().get_service());
3396     int newCropFrame = (int) newCropStart.frames(m_fps);
3397     Mlt::Tractor tractor(service);
3398     Mlt::Producer trackProducer(tractor.track(info.track));
3399     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3400     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3401         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3402         return false;
3403     }
3404     service.lock();
3405     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3406     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3407     if (clip == NULL) {
3408         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3409         service.unlock();
3410         return false;
3411     }
3412     int previousStart = clip->get_in();
3413     int previousOut = clip->get_out();
3414     delete clip;
3415     if (previousStart == newCropFrame) {
3416         kDebug() << "////////  No ReSIZING Required";
3417         service.unlock();
3418         return true;
3419     }
3420     int frameOffset = newCropFrame - previousStart;
3421     trackPlaylist.resize_clip(clipIndex, newCropFrame, previousOut + frameOffset);
3422     service.unlock();
3423     m_mltConsumer->set("refresh", 1);
3424     return true;
3425 }
3426
3427 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff)
3428 {
3429     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
3430     Mlt::Service service(m_mltProducer->parent().get_service());
3431     int moveFrame = (int) diff.frames(m_fps);
3432     Mlt::Tractor tractor(service);
3433     Mlt::Producer trackProducer(tractor.track(info.track));
3434     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3435     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
3436         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
3437         return false;
3438     }
3439     service.lock();
3440     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
3441     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
3442     if (clip == NULL || clip->is_blank()) {
3443         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
3444         service.unlock();
3445         return false;
3446     }
3447     int previousStart = clip->get_in();
3448     int previousOut = clip->get_out();
3449
3450     previousStart += moveFrame;
3451
3452     if (previousStart < 0) {
3453         // this is possible for images and color clips
3454         previousOut -= previousStart;
3455         previousStart = 0;
3456     }
3457
3458     int length = previousOut + 1;
3459     if (length > clip->get_length()) {
3460         clip->parent().set("length", length + 1);
3461         clip->parent().set("out", length);
3462         clip->set("length", length + 1);
3463     }
3464     delete clip;
3465
3466     // kDebug() << "RESIZE, new start: " << previousStart << ", " << previousOut;
3467     trackPlaylist.resize_clip(clipIndex, previousStart, previousOut);
3468     if (moveFrame > 0) {
3469         trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
3470     } else {
3471         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
3472         int blankIndex = clipIndex - 1;
3473         int blankLength = trackPlaylist.clip_length(blankIndex);
3474         // kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
3475         if (! trackPlaylist.is_blank(blankIndex)) {
3476             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
3477         }
3478         if (blankLength + moveFrame == 0)
3479             trackPlaylist.remove(blankIndex);
3480         else
3481             trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
3482     }
3483     trackPlaylist.consolidate_blanks(0);
3484     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
3485         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
3486         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
3487         ItemInfo transpinfo;
3488         transpinfo.startPos = info.startPos + diff;
3489         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
3490         transpinfo.track = info.track;
3491         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
3492     }*/
3493     //m_mltConsumer->set("refresh", 1);
3494     service.unlock();
3495     m_mltConsumer->set("refresh", 1);
3496     return true;
3497 }
3498
3499 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod, bool overwrite, bool insert)
3500 {
3501     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod, overwrite, insert);
3502 }
3503
3504
3505 bool Render::mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod)
3506 {
3507     if (prod == NULL || !prod->is_valid() || tractor == NULL || !tractor->is_valid()) {
3508         kDebug() << "// Warning, CLIP on track " << track << ", at: " << pos << " is invalid, cannot update it!!!";
3509         return false;
3510     }
3511
3512     Mlt::Producer trackProducer(tractor->track(track));
3513     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3514     int clipIndex = trackPlaylist.get_clip_index_at(pos);
3515     Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3516     if (clipProducer == NULL || clipProducer->is_blank()) {
3517         kDebug() << "// ERROR UPDATING CLIP PROD";
3518         delete clipProducer;
3519         return false;
3520     }
3521     Mlt::Producer *clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3522     if (!clip || !clip->is_valid()) {
3523         if (clip) delete clip;
3524         delete clipProducer;
3525         return false;
3526     }
3527     // move all effects to the correct producer
3528     mltPasteEffects(clipProducer, clip);
3529     trackPlaylist.insert_at(pos, clip, 1);
3530     delete clip;
3531     delete clipProducer;
3532     return true;
3533 }
3534
3535 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod, bool overwrite, bool /*insert*/)
3536 {
3537     Mlt::Service service(m_mltProducer->parent().get_service());
3538     if (service.type() != tractor_type) {
3539         kWarning() << "// TRACTOR PROBLEM";
3540         return false;
3541     }
3542
3543     Mlt::Tractor tractor(service);
3544     service.lock();
3545     Mlt::Producer trackProducer(tractor.track(startTrack));
3546     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3547     int clipIndex = trackPlaylist.get_clip_index_at(moveStart);
3548     int clipDuration = trackPlaylist.clip_length(clipIndex);
3549     bool checkLength = false;
3550     if (endTrack == startTrack) {
3551         Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3552         if (!overwrite) {
3553             bool success = true;
3554             if (!trackPlaylist.is_blank_at(moveEnd) || !clipProducer || !clipProducer->is_valid() || clipProducer->is_blank()) {
3555                 success = false;
3556             }
3557             else {
3558                 // Check that the destination region is empty
3559                 trackPlaylist.consolidate_blanks(0);
3560                 int destinationIndex = trackPlaylist.get_clip_index_at(moveEnd);
3561                 if (destinationIndex < trackPlaylist.count() - 1) {
3562                     // We are not at the end of the track
3563                     int blankSize = trackPlaylist.blanks_from(destinationIndex, 1);
3564                     // Make sure we have enough place to insert clip
3565                     if (blankSize - clipDuration - (moveEnd - trackPlaylist.clip_start(destinationIndex)) < 0) success = false;
3566                 }
3567             }
3568             if (!success) {
3569                 if (clipProducer) {
3570                     trackPlaylist.insert_at(moveStart, clipProducer, 1);
3571                     delete clipProducer;
3572                 }
3573                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3574                 service.unlock();
3575                 return false;
3576             }
3577         }
3578         
3579         if (overwrite) {
3580             trackPlaylist.remove_region(moveEnd, clipProducer->get_playtime());
3581             int clipIndex = trackPlaylist.get_clip_index_at(moveEnd);
3582             trackPlaylist.insert_blank(clipIndex, clipProducer->get_playtime() - 1);
3583         }
3584         int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
3585         if (newIndex == -1) {
3586             kDebug()<<"// CANNOT MOVE CLIP TO: "<<moveEnd;
3587             trackPlaylist.insert_at(moveStart, clipProducer, 1);
3588             delete clipProducer;
3589             service.unlock();
3590             return false;
3591         }
3592         trackPlaylist.consolidate_blanks(1);
3593         delete clipProducer;
3594         if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
3595     } else {
3596         Mlt::Producer destTrackProducer(tractor.track(endTrack));
3597         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
3598         if (!overwrite && !destTrackPlaylist.is_blank_at(moveEnd)) {
3599             // error, destination is not empty
3600             kDebug() << "Cannot move: Destination is not empty";
3601             service.unlock();
3602             return false;
3603         } else {
3604             Mlt::Producer *clipProducer = trackPlaylist.replace_with_blank(clipIndex);
3605             if (!clipProducer || clipProducer->is_blank()) {
3606                 // error, destination is not empty
3607                 //int ix = trackPlaylist.get_clip_index_at(moveEnd);
3608                 if (clipProducer) delete clipProducer;
3609                 kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
3610                 service.unlock();
3611                 return false;
3612             }
3613             trackPlaylist.consolidate_blanks(0);
3614             destTrackPlaylist.consolidate_blanks(1);
3615             Mlt::Producer *clip;
3616             // check if we are moving a slowmotion producer
3617             QString serv = clipProducer->parent().get("mlt_service");
3618             QString currentid = clipProducer->parent().get("id");
3619             if (serv == "framebuffer") {
3620                 clip = clipProducer;
3621             } else {
3622                 if (prod == NULL) {
3623                     // Special case: prod is null when using placeholder clips.
3624                     // in that case, use the producer existing in playlist. Note that
3625                     // it will bypass the one producer per track logic and might cause
3626                     // Sound cracks if clip is moved so that it overlaps another copy of itself
3627                     clip = clipProducer->cut(clipProducer->get_in(), clipProducer->get_out());
3628                 } else clip = prod->cut(clipProducer->get_in(), clipProducer->get_out());
3629             }
3630
3631             // move all effects to the correct producer
3632             mltPasteEffects(clipProducer, clip);
3633
3634             if (overwrite) {
3635                 destTrackPlaylist.remove_region(moveEnd, clip->get_playtime());
3636                 int clipIndex = destTrackPlaylist.get_clip_index_at(moveEnd);
3637                 destTrackPlaylist.insert_blank(clipIndex, clip->get_playtime() - 1);
3638             }
3639
3640             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
3641
3642             if (clip == clipProducer) {
3643                 delete clip;
3644                 clip = NULL;
3645             } else {
3646                 delete clip;
3647                 delete clipProducer;
3648             }
3649             destTrackPlaylist.consolidate_blanks(0);
3650             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
3651                 kDebug() << "//////// moving clip transparency";
3652                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
3653             }*/
3654             if (clipIndex > trackPlaylist.count()) checkLength = true;
3655             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
3656         }
3657     }
3658     service.unlock();
3659     if (checkLength) mltCheckLength(&tractor);
3660     //askForRefresh();
3661     //m_mltConsumer->set("refresh", 1);
3662     return true;
3663 }
3664
3665
3666 QList <int> Render::checkTrackSequence(int track)
3667 {
3668     QList <int> list;
3669     Mlt::Service service(m_mltProducer->parent().get_service());
3670     if (service.type() != tractor_type) {
3671         kWarning() << "// TRACTOR PROBLEM";
3672         return list;
3673     }
3674     Mlt::Tractor tractor(service);
3675     service.lock();
3676     Mlt::Producer trackProducer(tractor.track(track));
3677     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
3678     int clipNb = trackPlaylist.count();
3679     //kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
3680     for (int i = 0; i < clipNb; i++) {
3681         Mlt::Producer *c = trackPlaylist.get_clip(i);
3682         int pos = trackPlaylist.clip_start(i);
3683         if (!list.contains(pos)) list.append(pos);
3684         pos += c->get_playtime();
3685         if (!list.contains(pos)) list.append(pos);
3686         delete c;
3687     }
3688     return list;
3689 }
3690
3691 bool Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut)
3692 {
3693     int new_in = (int)newIn.frames(m_fps);
3694     int new_out = (int)newOut.frames(m_fps) - 1;
3695     if (new_in >= new_out) return false;
3696     int old_in = (int)oldIn.frames(m_fps);
3697     int old_out = (int)oldOut.frames(m_fps) - 1;
3698
3699     Mlt::Service service(m_mltProducer->parent().get_service());
3700     Mlt::Tractor tractor(service);
3701     Mlt::Field *field = tractor.field();
3702
3703     bool doRefresh = true;
3704     // Check if clip is visible in monitor
3705     int diff = old_out - m_mltProducer->position();
3706     if (diff < 0 || diff > old_out - old_in) doRefresh = false;
3707     if (doRefresh) {
3708         diff = new_out - m_mltProducer->position();
3709         if (diff < 0 || diff > new_out - new_in) doRefresh = false;
3710     }
3711     service.lock();
3712
3713     mlt_service nextservice = mlt_service_get_producer(service.get_service());
3714     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3715     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3716     QString resource = mlt_properties_get(properties, "mlt_service");
3717     int old_pos = (int)(old_in + old_out) / 2;
3718     bool found = false;
3719
3720     while (mlt_type == "transition") {
3721         Mlt::Transition transition((mlt_transition) nextservice);
3722         nextservice = mlt_service_producer(nextservice);
3723         int currentTrack = transition.get_b_track();
3724         int currentIn = (int) transition.get_in();
3725         int currentOut = (int) transition.get_out();
3726
3727         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3728             found = true;
3729             if (newTrack - startTrack != 0) {
3730                 Mlt::Properties trans_props(transition.get_properties());
3731                 Mlt::Transition new_transition(*m_mltProfile, transition.get("mlt_service"));
3732                 Mlt::Properties new_trans_props(new_transition.get_properties());
3733                 new_trans_props.inherit(trans_props);
3734                 new_transition.set_in_and_out(new_in, new_out);
3735                 field->disconnect_service(transition);
3736                 mltPlantTransition(field, new_transition, newTransitionTrack, newTrack);
3737                 //field->plant_transition(new_transition, newTransitionTrack, newTrack);
3738             } else transition.set_in_and_out(new_in, new_out);
3739             break;
3740         }
3741         if (nextservice == NULL) break;
3742         properties = MLT_SERVICE_PROPERTIES(nextservice);
3743         mlt_type = mlt_properties_get(properties, "mlt_type");
3744         resource = mlt_properties_get(properties, "mlt_service");
3745     }
3746     service.unlock();
3747     if (doRefresh) refresh();
3748     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3749     return found;
3750 }
3751
3752
3753 void Render::mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track)
3754 {
3755     mlt_service nextservice = mlt_service_get_producer(field->get_service());
3756     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3757     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3758     QString resource = mlt_properties_get(properties, "mlt_service");
3759     QList <Mlt::Transition *> trList;
3760     mlt_properties insertproperties = tr.get_properties();
3761     QString insertresource = mlt_properties_get(insertproperties, "mlt_service");
3762     bool isMixTransition = insertresource == "mix";
3763
3764     while (mlt_type == "transition") {
3765         Mlt::Transition transition((mlt_transition) nextservice);
3766         nextservice = mlt_service_producer(nextservice);
3767         int aTrack = transition.get_a_track();
3768         int bTrack = transition.get_b_track();
3769         if ((isMixTransition || resource != "mix") && (aTrack < a_track || (aTrack == a_track && bTrack > b_track))) {
3770             Mlt::Properties trans_props(transition.get_properties());
3771             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
3772             Mlt::Properties new_trans_props(cp->get_properties());
3773             new_trans_props.inherit(trans_props);
3774             trList.append(cp);
3775             field->disconnect_service(transition);
3776         }
3777         //else kDebug() << "// FOUND TRANS OK, "<<resource<< ", A_: " << aTrack << ", B_ "<<bTrack;
3778
3779         if (nextservice == NULL) break;
3780         properties = MLT_SERVICE_PROPERTIES(nextservice);
3781         mlt_type = mlt_properties_get(properties, "mlt_type");
3782         resource = mlt_properties_get(properties, "mlt_service");
3783     }
3784     field->plant_transition(tr, a_track, b_track);
3785
3786     // re-add upper transitions
3787     for (int i = trList.count() - 1; i >= 0; i--) {
3788         //kDebug()<< "REPLANT ON TK: "<<trList.at(i)->get_a_track()<<", "<<trList.at(i)->get_b_track();
3789         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
3790     }
3791     qDeleteAll(trList);
3792 }
3793
3794 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force)
3795 {
3796     if (oldTag == tag && !force) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
3797     else {
3798         //kDebug()<<"// DELETING TRANS: "<<a_track<<"-"<<b_track;
3799         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
3800         mltAddTransition(tag, a_track, b_track, in, out, xml, false);
3801     }
3802
3803     if (m_mltProducer->position() >= in.frames(m_fps) && m_mltProducer->position() <= out.frames(m_fps)) refresh();
3804 }
3805
3806 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml)
3807 {
3808     mlt_service serv = m_mltProducer->parent().get_service();
3809     mlt_service_lock(serv);
3810
3811     mlt_service nextservice = mlt_service_get_producer(serv);
3812     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3813     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3814     QString resource = mlt_properties_get(properties, "mlt_service");
3815     int in_pos = (int) in.frames(m_fps);
3816     int out_pos = (int) out.frames(m_fps) - 1;
3817
3818     while (mlt_type == "transition") {
3819         mlt_transition tr = (mlt_transition) nextservice;
3820         int currentTrack = mlt_transition_get_b_track(tr);
3821         int currentBTrack = mlt_transition_get_a_track(tr);
3822         int currentIn = (int) mlt_transition_get_in(tr);
3823         int currentOut = (int) mlt_transition_get_out(tr);
3824
3825         // kDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos;
3826         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
3827             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
3828             QMap<QString, QString>::Iterator it;
3829             QString key;
3830             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
3831
3832             QString currentId = mlt_properties_get(transproperties, "kdenlive_id");
3833             if (currentId != xml.attribute("id")) {
3834                 // The transition ID is not the same, so reset all properties
3835                 mlt_properties_set(transproperties, "kdenlive_id", xml.attribute("id").toUtf8().constData());
3836                 // Cleanup previous properties
3837                 QStringList permanentProps;
3838                 permanentProps << "factory" << "kdenlive_id" << "mlt_service" << "mlt_type" << "in";
3839                 permanentProps << "out" << "a_track" << "b_track";
3840                 for (int i = 0; i < mlt_properties_count(transproperties); i++) {
3841                     QString propName = mlt_properties_get_name(transproperties, i);
3842                     if (!propName.startsWith('_') && ! permanentProps.contains(propName)) {
3843                         mlt_properties_set(transproperties, propName.toUtf8().constData(), "");
3844                     }
3845                 }
3846             }
3847
3848             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
3849             mlt_properties_set_int(transproperties, "automatic", xml.attribute("automatic", "0").toInt());
3850
3851             if (currentBTrack != a_track) {
3852                 mlt_properties_set_int(transproperties, "a_track", a_track);
3853             }
3854             for (it = map.begin(); it != map.end(); ++it) {
3855                 key = it.key();
3856                 mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData());
3857                 //kDebug() << " ------  UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData();
3858                 //filter->set("kdenlive_id", id);
3859             }
3860             break;
3861         }
3862         nextservice = mlt_service_producer(nextservice);
3863         if (nextservice == NULL) break;
3864         properties = MLT_SERVICE_PROPERTIES(nextservice);
3865         mlt_type = mlt_properties_get(properties, "mlt_type");
3866         resource = mlt_properties_get(properties, "mlt_service");
3867     }
3868     mlt_service_unlock(serv);
3869     //askForRefresh();
3870     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3871 }
3872
3873 void Render::mltDeleteTransition(QString tag, int /*a_track*/, int b_track, GenTime in, GenTime out, QDomElement /*xml*/, bool /*do_refresh*/)
3874 {
3875     mlt_service serv = m_mltProducer->parent().get_service();
3876     mlt_service_lock(serv);
3877
3878     Mlt::Service service(serv);
3879     Mlt::Tractor tractor(service);
3880     Mlt::Field *field = tractor.field();
3881
3882     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3883
3884     mlt_service nextservice = mlt_service_get_producer(serv);
3885     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3886     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3887     QString resource = mlt_properties_get(properties, "mlt_service");
3888
3889     const int old_pos = (int)((in + out).frames(m_fps) / 2);
3890     //kDebug() << " del trans pos: " << in.frames(25) << "-" << out.frames(25);
3891
3892     while (mlt_type == "transition") {
3893         mlt_transition tr = (mlt_transition) nextservice;
3894         int currentTrack = mlt_transition_get_b_track(tr);
3895         int currentIn = (int) mlt_transition_get_in(tr);
3896         int currentOut = (int) mlt_transition_get_out(tr);
3897         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3898
3899         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
3900             mlt_field_disconnect_service(field->get_field(), nextservice);
3901             break;
3902         }
3903         nextservice = mlt_service_producer(nextservice);
3904         if (nextservice == NULL) break;
3905         properties = MLT_SERVICE_PROPERTIES(nextservice);
3906         mlt_type = mlt_properties_get(properties, "mlt_type");
3907         resource = mlt_properties_get(properties, "mlt_service");
3908     }
3909     mlt_service_unlock(serv);
3910     //askForRefresh();
3911     //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1);
3912 }
3913
3914 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml)
3915 {
3916     QDomNodeList attribs = xml.elementsByTagName("parameter");
3917     QMap<QString, QString> map;
3918     for (int i = 0; i < attribs.count(); i++) {
3919         QDomElement e = attribs.item(i).toElement();
3920         QString name = e.attribute("name");
3921         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
3922         map[name] = e.attribute("default");
3923         if (!e.attribute("value").isEmpty()) {
3924             map[name] = e.attribute("value");
3925         }
3926         if (e.attribute("type") != "addedgeometry" && (e.attribute("factor", "1") != "1" || e.attribute("offset", "0") != "0")) {
3927             map[name] = m_locale.toString((map.value(name).toDouble() - e.attribute("offset", "0").toDouble()) / e.attribute("factor", "1").toDouble());
3928             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
3929         }
3930
3931         if (e.attribute("namedesc").contains(';')) {
3932             QString format = e.attribute("format");
3933             QStringList separators = format.split("%d", QString::SkipEmptyParts);
3934             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
3935             QString neu;
3936             QTextStream txtNeu(&neu);
3937             if (values.size() > 0)
3938                 txtNeu << (int)values[0].toDouble();
3939             int i = 0;
3940             for (i = 0; i < separators.size() && i + 1 < values.size(); i++) {
3941                 txtNeu << separators[i];
3942                 txtNeu << (int)(values[i+1].toDouble());
3943             }
3944             if (i < separators.size())
3945                 txtNeu << separators[i];
3946             map[e.attribute("name")] = neu;
3947         }
3948
3949     }
3950     return map;
3951 }
3952
3953 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id)
3954 {
3955     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
3956     Mlt::Service service(m_mltProducer->parent().get_service());
3957     Mlt::Tractor tractor(service);
3958     Mlt::Field *field = tractor.field();
3959
3960     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
3961     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
3962     transition->set("transparency", id);
3963     transition->set("fill", 1);
3964     transition->set("internal_added", 237);
3965     field->plant_transition(*transition, transitiontrack, info.track);
3966     refresh();
3967 }
3968
3969 void Render::mltDeleteTransparency(int pos, int track, int id)
3970 {
3971     Mlt::Service service(m_mltProducer->parent().get_service());
3972     Mlt::Tractor tractor(service);
3973     Mlt::Field *field = tractor.field();
3974
3975     //if (do_refresh) m_mltConsumer->set("refresh", 0);
3976     mlt_service serv = m_mltProducer->parent().get_service();
3977
3978     mlt_service nextservice = mlt_service_get_producer(serv);
3979     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
3980     QString mlt_type = mlt_properties_get(properties, "mlt_type");
3981     QString resource = mlt_properties_get(properties, "mlt_service");
3982
3983     while (mlt_type == "transition") {
3984         mlt_transition tr = (mlt_transition) nextservice;
3985         int currentTrack = mlt_transition_get_b_track(tr);
3986         int currentIn = (int) mlt_transition_get_in(tr);
3987         int currentOut = (int) mlt_transition_get_out(tr);
3988         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
3989         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
3990
3991         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
3992             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
3993             mlt_field_disconnect_service(field->get_field(), nextservice);
3994             break;
3995         }
3996         nextservice = mlt_service_producer(nextservice);
3997         if (nextservice == NULL) break;
3998         properties = MLT_SERVICE_PROPERTIES(nextservice);
3999         mlt_type = mlt_properties_get(properties, "mlt_type");
4000         resource = mlt_properties_get(properties, "mlt_service");
4001     }
4002     //if (do_refresh) m_mltConsumer->set("refresh", 1);
4003 }
4004
4005 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id)
4006 {
4007     Mlt::Service service(m_mltProducer->parent().get_service());
4008     Mlt::Tractor tractor(service);
4009
4010     service.lock();
4011     m_mltConsumer->set("refresh", 0);
4012
4013     mlt_service serv = m_mltProducer->parent().get_service();
4014     mlt_service nextservice = mlt_service_get_producer(serv);
4015     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4016     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4017     QString resource = mlt_properties_get(properties, "mlt_service");
4018     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << 'x' << newEnd << ", " << track << ", " << id;
4019     while (mlt_type == "transition") {
4020         mlt_transition tr = (mlt_transition) nextservice;
4021         int currentTrack = mlt_transition_get_b_track(tr);
4022         int currentIn = (int) mlt_transition_get_in(tr);
4023         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
4024         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4025         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << 'x' << transitionId ;
4026         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
4027             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << 'x' << newEnd;
4028             mlt_transition_set_in_and_out(tr, newStart, newEnd);
4029             break;
4030         }
4031         nextservice = mlt_service_producer(nextservice);
4032         if (nextservice == NULL) break;
4033         properties = MLT_SERVICE_PROPERTIES(nextservice);
4034         mlt_type = mlt_properties_get(properties, "mlt_type");
4035         resource = mlt_properties_get(properties, "mlt_service");
4036     }
4037     service.unlock();
4038     m_mltConsumer->set("refresh", 1);
4039
4040 }
4041
4042 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id)
4043 {
4044     Mlt::Service service(m_mltProducer->parent().get_service());
4045     Mlt::Tractor tractor(service);
4046
4047     service.lock();
4048     m_mltConsumer->set("refresh", 0);
4049
4050     mlt_service serv = m_mltProducer->parent().get_service();
4051     mlt_service nextservice = mlt_service_get_producer(serv);
4052     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4053     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4054     QString resource = mlt_properties_get(properties, "mlt_service");
4055
4056     while (mlt_type == "transition") {
4057         mlt_transition tr = (mlt_transition) nextservice;
4058         int currentTrack = mlt_transition_get_b_track(tr);
4059         int currentaTrack = mlt_transition_get_a_track(tr);
4060         int currentIn = (int) mlt_transition_get_in(tr);
4061         int currentOut = (int) mlt_transition_get_out(tr);
4062         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4063         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
4064         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<'x'<<startTrack;
4065         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
4066             kDebug() << "//////MOVING";
4067             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
4068             if (endTrack != startTrack) {
4069                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
4070                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
4071                 mlt_properties_set_int(properties, "b_track", endTrack);
4072             }
4073             break;
4074         }
4075         nextservice = mlt_service_producer(nextservice);
4076         if (nextservice == NULL) break;
4077         properties = MLT_SERVICE_PROPERTIES(nextservice);
4078         mlt_type = mlt_properties_get(properties, "mlt_type");
4079         resource = mlt_properties_get(properties, "mlt_service");
4080     }
4081     service.unlock();
4082     m_mltConsumer->set("refresh", 1);
4083 }
4084
4085
4086 bool Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh)
4087 {
4088     if (in >= out) return false;
4089     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
4090     Mlt::Service service(m_mltProducer->parent().get_service());
4091
4092     Mlt::Tractor tractor(service);
4093     Mlt::Field *field = tractor.field();
4094
4095     Mlt::Transition transition(*m_mltProfile, tag.toUtf8().constData());
4096     if (out != GenTime())
4097         transition.set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
4098
4099     if (do_refresh && (m_mltProducer->position() < in.frames(m_fps) || m_mltProducer->position() > out.frames(m_fps))) do_refresh = false;
4100     QMap<QString, QString>::Iterator it;
4101     QString key;
4102     if (xml.attribute("automatic") == "1") transition.set("automatic", 1);
4103     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
4104     if (xml.hasAttribute("id"))
4105         transition.set("kdenlive_id", xml.attribute("id").toUtf8().constData());
4106     if (xml.hasAttribute("force_track"))
4107         transition.set("force_track", xml.attribute("force_track").toInt());
4108
4109     for (it = args.begin(); it != args.end(); ++it) {
4110         key = it.key();
4111         if (!it.value().isEmpty())
4112             transition.set(key.toUtf8().constData(), it.value().toUtf8().constData());
4113         //kDebug() << " ------  ADDING TRANS PARAM: " << key << ": " << it.value();
4114     }
4115     // attach transition
4116     service.lock();
4117     mltPlantTransition(field, transition, a_track, b_track);
4118     // field->plant_transition(*transition, a_track, b_track);
4119     service.unlock();
4120     if (do_refresh) refresh();
4121     return true;
4122 }
4123
4124 void Render::mltSavePlaylist()
4125 {
4126     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
4127     Mlt::Consumer fileConsumer(*m_mltProfile, "xml");
4128     fileConsumer.set("resource", "/tmp/playlist.mlt");
4129
4130     Mlt::Service service(m_mltProducer->get_service());
4131
4132     fileConsumer.connect(service);
4133     fileConsumer.start();
4134 }
4135
4136 const QList <Mlt::Producer *> Render::producersList()
4137 {
4138     QList <Mlt::Producer *> prods;
4139     if (m_mltProducer == NULL) return prods;
4140     Mlt::Service service(m_mltProducer->parent().get_service());
4141     if (service.type() != tractor_type) return prods;
4142     Mlt::Tractor tractor(service);
4143     QStringList ids;
4144
4145     int trackNb = tractor.count();
4146     for (int t = 1; t < trackNb; t++) {
4147         Mlt::Producer *tt = tractor.track(t);
4148         Mlt::Producer trackProducer(tt);
4149         delete tt;
4150         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4151         if (!trackPlaylist.is_valid()) continue;
4152         int clipNb = trackPlaylist.count();
4153         for (int i = 0; i < clipNb; i++) {
4154             Mlt::Producer *c = trackPlaylist.get_clip(i);
4155             if (c == NULL) continue;
4156             QString prodId = c->parent().get("id");
4157             if (!c->is_blank() && !ids.contains(prodId) && !prodId.startsWith("slowmotion") && !prodId.isEmpty()) {
4158                 Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4159                 if (nprod) {
4160                     ids.append(prodId);
4161                     prods.append(nprod);
4162                 }
4163             }
4164             delete c;
4165         }
4166     }
4167     return prods;
4168 }
4169
4170 void Render::fillSlowMotionProducers()
4171 {
4172     if (m_mltProducer == NULL) return;
4173     Mlt::Service service(m_mltProducer->parent().get_service());
4174     if (service.type() != tractor_type) return;
4175
4176     Mlt::Tractor tractor(service);
4177
4178     int trackNb = tractor.count();
4179     for (int t = 1; t < trackNb; t++) {
4180         Mlt::Producer *tt = tractor.track(t);
4181         Mlt::Producer trackProducer(tt);
4182         delete tt;
4183         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
4184         if (!trackPlaylist.is_valid()) continue;
4185         int clipNb = trackPlaylist.count();
4186         for (int i = 0; i < clipNb; i++) {
4187             Mlt::Producer *c = trackPlaylist.get_clip(i);
4188             Mlt::Producer *nprod = new Mlt::Producer(c->get_parent());
4189             if (nprod) {
4190                 QString id = nprod->parent().get("id");
4191                 if (id.startsWith("slowmotion:") && !nprod->is_blank()) {
4192                     // this is a slowmotion producer, add it to the list
4193                     QString url = QString::fromUtf8(nprod->get("resource"));
4194                     int strobe = nprod->get_int("strobe");
4195                     if (strobe > 1) url.append("&strobe=" + QString::number(strobe));
4196                     if (!m_slowmotionProducers.contains(url)) {
4197                         m_slowmotionProducers.insert(url, nprod);
4198                     }
4199                 } else delete nprod;
4200             }
4201             delete c;
4202         }
4203     }
4204 }
4205
4206 QList <TransitionInfo> Render::mltInsertTrack(int ix, bool videoTrack)
4207 {
4208     Mlt::Service service(m_mltProducer->parent().get_service());
4209     if (service.type() != tractor_type) {
4210         kWarning() << "// TRACTOR PROBLEM";
4211         return QList <TransitionInfo> ();
4212     }
4213     blockSignals(true);
4214     service.lock();
4215     Mlt::Tractor tractor(service);
4216     QList <TransitionInfo> transitionInfos;
4217     Mlt::Playlist playlist;
4218     int ct = tractor.count();
4219     if (ix > ct) {
4220         kDebug() << "// ERROR, TRYING TO insert TRACK " << ix << ", max: " << ct;
4221         ix = ct;
4222     }
4223
4224     int pos = ix;
4225     if (pos < ct) {
4226         Mlt::Producer *prodToMove = new Mlt::Producer(tractor.track(pos));
4227         tractor.set_track(playlist, pos);
4228         Mlt::Producer newProd(tractor.track(pos));
4229         if (!videoTrack) newProd.set("hide", 1);
4230         pos++;
4231         for (; pos <= ct; pos++) {
4232             Mlt::Producer *prodToMove2 = new Mlt::Producer(tractor.track(pos));
4233             tractor.set_track(*prodToMove, pos);
4234             prodToMove = prodToMove2;
4235         }
4236     } else {
4237         tractor.set_track(playlist, ix);
4238         Mlt::Producer newProd(tractor.track(ix));
4239         if (!videoTrack) newProd.set("hide", 1);
4240     }
4241     checkMaxThreads();
4242
4243     // Move transitions
4244     mlt_service serv = m_mltProducer->parent().get_service();
4245     mlt_service nextservice = mlt_service_get_producer(serv);
4246     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
4247     QString mlt_type = mlt_properties_get(properties, "mlt_type");
4248     QString resource = mlt_properties_get(properties, "mlt_service");
4249     Mlt::Field *field = tractor.field();
4250     QList <Mlt::Transition *> trList;
4251
4252     while (mlt_type == "transition") {
4253         if (resource != "mix") {
4254             Mlt::Transition transition((mlt_transition) nextservice);
4255             nextservice = mlt_service_producer(nextservice);
4256             int currentbTrack = transition.get_b_track();
4257             int currentaTrack = transition.get_a_track();
4258             bool trackChanged = false;
4259             bool forceTransitionTrack = false;
4260             if (currentbTrack >= ix) {
4261                 if (currentbTrack == ix && currentaTrack < ix) forceTransitionTrack = true;
4262                 currentbTrack++;
4263                 trackChanged = true;
4264             }
4265             if (currentaTrack >= ix) {
4266                 currentaTrack++;
4267                 trackChanged = true;
4268             }
4269             kDebug()<<"// Newtrans: "<<currentaTrack<<"/"<<currentbTrack;
4270             
4271             // disconnect all transitions
4272             Mlt::Properties trans_props(transition.get_properties());
4273             Mlt::Transition *cp = new Mlt::Transition(*m_mltProfile, transition.get("mlt_service"));
4274             Mlt::Properties new_trans_props(cp->get_properties());
4275             new_trans_props.inherit(trans_props);
4276             
4277             if (trackChanged) {
4278                 // Transition track needs to be adjusted
4279                 cp->set("a_track", currentaTrack);
4280                 cp->set("b_track", currentbTrack);
4281                 // Check if transition track was changed and needs to be forced
4282                 if (forceTransitionTrack) cp->set("force_track", 1);
4283                 TransitionInfo trInfo;
4284                 trInfo.startPos = GenTime(transition.get_in(), m_fps);
4285                 trInfo.a_track = currentaTrack;
4286                 trInfo.b_track = currentbTrack;
4287                 trInfo.forceTrack = cp->get_int("force_track");
4288                 transitionInfos.append(trInfo);
4289             }
4290             trList.append(cp);
4291             field->disconnect_service(transition);
4292         }
4293         else nextservice = mlt_service_producer(nextservice);
4294         if (nextservice == NULL) break;
4295         properties = MLT_SERVICE_PROPERTIES(nextservice);
4296         mlt_type = mlt_properties_get(properties, "mlt_type");
4297         resource = mlt_properties_get(properties, "mlt_service");
4298     }
4299
4300     // Add audio mix transition to last track
4301     Mlt::Transition transition(*m_mltProfile, "mix");
4302     transition.set("a_track", 1);
4303     transition.set("b_track", ct);
4304     transition.set("always_active", 1);
4305     transition.set("internal_added", 237);
4306     transition.set("combine", 1);
4307     mltPlantTransition(field, transition, 1, ct);
4308     
4309     // re-add transitions
4310     for (int i = trList.count() - 1; i >= 0; i--) {
4311         field->plant_transition(*trList.at(i), trList.at(i)->get_a_track(), trList.at(i)->get_b_track());
4312     }
4313     qDeleteAll(trList);
4314     
4315     service.unlock();
4316     blockSignals(false);
4317     return transitionInfos;
4318 }
4319
4320
4321 void Render::mltDeleteTrack(int ix)
4322 {
4323     QDomDocument doc;
4324     doc.setContent(sceneList(), false);
4325     int tracksCount = doc.elementsByTagName("track").count() - 1;
4326     QDomNode track = doc.elementsByTagName("track").at(ix);
4327     QDomNode tractor = doc.elementsByTagName("tractor").at(0);
4328     QDomNodeList transitions = doc.elementsByTagName("transition");
4329     for (int i = 0; i < transitions.count(); i++) {
4330         QDomElement e = transitions.at(i).toElement();
4331         QDomNodeList props = e.elementsByTagName("property");
4332         QMap <QString, QString> mappedProps;
4333         for (int j = 0; j < props.count(); j++) {
4334             QDomElement f = props.at(j).toElement();
4335             mappedProps.insert(f.attribute("name"), f.firstChild().nodeValue());
4336         }
4337         if (mappedProps.value("mlt_service") == "mix" && mappedProps.value("b_track").toInt() == tracksCount) {
4338             tractor.removeChild(transitions.at(i));
4339             i--;
4340         } else if (mappedProps.value("mlt_service") != "mix" && (mappedProps.value("b_track").toInt() >= ix || mappedProps.value("a_track").toInt() >= ix)) {
4341             // Transition needs to be moved
4342             int a_track = mappedProps.value("a_track").toInt();
4343             int b_track = mappedProps.value("b_track").toInt();
4344             if (a_track > 0 && a_track >= ix) a_track --;
4345             if (b_track == ix) {
4346                 // transition was on the deleted track, so remove it
4347                 tractor.removeChild(transitions.at(i));
4348                 i--;
4349                 continue;
4350             }
4351             if (b_track > 0 && b_track > ix) b_track --;
4352             for (int j = 0; j < props.count(); j++) {
4353                 QDomElement f = props.at(j).toElement();
4354                 if (f.attribute("name") == "a_track") f.firstChild().setNodeValue(QString::number(a_track));
4355                 else if (f.attribute("name") == "b_track") f.firstChild().setNodeValue(QString::number(b_track));
4356             }
4357
4358         }
4359     }
4360     tractor.removeChild(track);
4361     //kDebug() << "/////////// RESULT SCENE: \n" << doc.toString();
4362     setSceneList(doc.toString(), m_mltConsumer->position());
4363     emit refreshDocumentProducers(false, false);
4364 }
4365
4366
4367 void Render::updatePreviewSettings()
4368 {
4369     kDebug() << "////// RESTARTING CONSUMER";
4370     if (!m_mltConsumer || !m_mltProducer) return;
4371     if (m_mltProducer->get_playtime() == 0) return;
4372     QMutexLocker locker(&m_mutex);
4373     Mlt::Service service(m_mltProducer->parent().get_service());
4374     if (service.type() != tractor_type) return;
4375
4376     //m_mltConsumer->set("refresh", 0);
4377     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
4378     m_mltConsumer->purge();
4379     QString scene = sceneList();
4380     int pos = 0;
4381     if (m_mltProducer) {
4382         pos = m_mltProducer->position();
4383     }
4384
4385     setSceneList(scene, pos);
4386 }
4387
4388
4389 QString Render::updateSceneListFps(double current_fps, double new_fps, QString scene)
4390 {
4391     // Update all frame positions to the new fps value
4392     //WARNING: there are probably some effects or other that hold a frame value
4393     // as parameter and will also need to be updated here!
4394     QDomDocument doc;
4395     doc.setContent(scene);
4396
4397     double factor = new_fps / current_fps;
4398     QDomNodeList producers = doc.elementsByTagName("producer");
4399     for (int i = 0; i < producers.count(); i++) {
4400         QDomElement prod = producers.at(i).toElement();
4401         prod.removeAttribute("in");
4402         prod.removeAttribute("out");
4403
4404         QDomNodeList props = prod.childNodes();
4405         for (int j = 0; j < props.count(); j++) {
4406             QDomElement param =  props.at(j).toElement();
4407             QString paramName = param.attribute("name");
4408             if (paramName.startsWith("meta.") || paramName == "length") {
4409                 prod.removeChild(props.at(j));
4410                 j--;
4411             }
4412         }
4413     }
4414
4415     QDomNodeList entries = doc.elementsByTagName("entry");
4416     for (int i = 0; i < entries.count(); i++) {
4417         QDomElement entry = entries.at(i).toElement();
4418         int in = entry.attribute("in").toInt();
4419         int out = entry.attribute("out").toInt();
4420         in = factor * in + 0.5;
4421         out = factor * out + 0.5;
4422         entry.setAttribute("in", in);
4423         entry.setAttribute("out", out);
4424     }
4425
4426     QDomNodeList blanks = doc.elementsByTagName("blank");
4427     for (int i = 0; i < blanks.count(); i++) {
4428         QDomElement blank = blanks.at(i).toElement();
4429         int length = blank.attribute("length").toInt();
4430         length = factor * length + 0.5;
4431         blank.setAttribute("length", QString::number(length));
4432     }
4433
4434     QDomNodeList filters = doc.elementsByTagName("filter");
4435     for (int i = 0; i < filters.count(); i++) {
4436         QDomElement filter = filters.at(i).toElement();
4437         int in = filter.attribute("in").toInt();
4438         int out = filter.attribute("out").toInt();
4439         in = factor * in + 0.5;
4440         out = factor * out + 0.5;
4441         filter.setAttribute("in", in);
4442         filter.setAttribute("out", out);
4443     }
4444
4445     QDomNodeList transitions = doc.elementsByTagName("transition");
4446     for (int i = 0; i < transitions.count(); i++) {
4447         QDomElement transition = transitions.at(i).toElement();
4448         int in = transition.attribute("in").toInt();
4449         int out = transition.attribute("out").toInt();
4450         in = factor * in + 0.5;
4451         out = factor * out + 0.5;
4452         transition.setAttribute("in", in);
4453         transition.setAttribute("out", out);
4454         QDomNodeList props = transition.childNodes();
4455         for (int j = 0; j < props.count(); j++) {
4456             QDomElement param =  props.at(j).toElement();
4457             QString paramName = param.attribute("name");
4458             if (paramName == "geometry") {
4459                 QString geom = param.firstChild().nodeValue();
4460                 QStringList keys = geom.split(';');
4461                 QStringList newKeys;
4462                 for (int k = 0; k < keys.size(); ++k) {
4463                     if (keys.at(k).contains('=')) {
4464                         int pos = keys.at(k).section('=', 0, 0).toInt();
4465                         pos = factor * pos + 0.5;
4466                         newKeys.append(QString::number(pos) + '=' + keys.at(k).section('=', 1));
4467                     } else newKeys.append(keys.at(k));
4468                 }
4469                 param.firstChild().setNodeValue(newKeys.join(";"));
4470             }
4471         }
4472     }
4473     QDomElement root = doc.documentElement();
4474     if (!root.isNull()) {
4475         QDomElement tractor = root.firstChildElement("tractor");
4476         int out = tractor.attribute("out").toInt();
4477         out = factor * out + 0.5;
4478         tractor.setAttribute("out", out);
4479         emit durationChanged(out);
4480     }
4481
4482     //kDebug() << "///////////////////////////// " << out << " \n" << doc.toString() << "\n-------------------------";
4483     return doc.toString();
4484 }
4485
4486
4487 void Render::sendFrameUpdate()
4488 {
4489     if (m_mltProducer) {
4490         Mlt::Frame * frame = m_mltProducer->get_frame();
4491         emitFrameUpdated(*frame);
4492         delete frame;
4493     }
4494 }
4495
4496 Mlt::Producer* Render::getProducer()
4497 {
4498     return m_mltProducer;
4499 }
4500
4501 const QString Render::activeClipId()
4502 {
4503     if (m_mltProducer) return m_mltProducer->get("id");
4504     return QString();
4505 }
4506
4507 //static 
4508 bool Render::getBlackMagicDeviceList(KComboBox *devicelist)
4509 {
4510     if (!KdenliveSettings::decklink_device_found()) return false;
4511     Mlt::Profile profile;
4512     Mlt::Producer bm(profile, "decklink");
4513     int found_devices = 0;
4514     if (bm.is_valid()) {
4515         bm.set("list_devices", 1);
4516         found_devices = bm.get_int("devices");
4517     }
4518     else KdenliveSettings::setDecklink_device_found(false);
4519     if (found_devices <= 0) {
4520         devicelist->setEnabled(false);
4521         return false;
4522     }
4523     for (int i = 0; i < found_devices; i++) {
4524         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4525         devicelist->addItem(bm.get(tmp));
4526         delete[] tmp;
4527     }
4528     return true;
4529 }
4530
4531 bool Render::getBlackMagicOutputDeviceList(KComboBox *devicelist)
4532 {
4533     if (!KdenliveSettings::decklink_device_found()) return false;
4534     Mlt::Profile profile;
4535     Mlt::Consumer bm(profile, "decklink");
4536     int found_devices = 0;
4537     if (bm.is_valid()) {
4538         bm.set("list_devices", 1);
4539         found_devices = bm.get_int("devices");
4540     }
4541     else KdenliveSettings::setDecklink_device_found(false);
4542     if (found_devices <= 0) {
4543         devicelist->setEnabled(false);
4544         return false;
4545     }
4546     for (int i = 0; i < found_devices; i++) {
4547         char *tmp = qstrdup(QString("device.%1").arg(i).toUtf8().constData());
4548         devicelist->addItem(bm.get(tmp));
4549         delete[] tmp;
4550     }
4551     return true;
4552 }
4553
4554 void Render::slotMultiStreamProducerFound(const QString path, QList<int> audio_list, QList<int> video_list, stringMap data)
4555
4556     if (KdenliveSettings::automultistreams()) {
4557         for (int i = 1; i < video_list.count(); i++) {
4558             int vindex = video_list.at(i);
4559             int aindex = 0;
4560             if (i <= audio_list.count() -1) {
4561                 aindex = audio_list.at(i);
4562             }
4563             data.insert("video_index", QString::number(vindex));
4564             data.insert("audio_index", QString::number(aindex));
4565             data.insert("bypassDuplicate", "1");
4566             emit addClip(KUrl(path), data);
4567         }
4568         return;
4569     }
4570     
4571     int width = 60.0 * m_mltProfile->dar();
4572     int swidth = 60.0 * m_mltProfile->width() / m_mltProfile->height();
4573     if (width % 2 == 1) width++;
4574
4575     KDialog dialog(qApp->activeWindow());
4576     dialog.setCaption("Multi Stream Clip");
4577     dialog.setButtons(KDialog::Ok | KDialog::Cancel);
4578     dialog.setButtonText(KDialog::Ok, i18n("Import selected clips"));
4579     QWidget *content = new QWidget(&dialog);
4580     dialog.setMainWidget(content);
4581     QVBoxLayout *vbox = new QVBoxLayout(content);
4582     QLabel *lab1 = new QLabel(i18n("Additional streams for clip\n %1", path), content);
4583     vbox->addWidget(lab1);
4584     QList <QGroupBox*> groupList;
4585     QList <QComboBox*> comboList;
4586     // We start loading the list at 1, video index 0 should already be loaded
4587     for (int j = 1; j < video_list.count(); j++) {
4588         Mlt::Producer multiprod(* m_mltProfile, path.toUtf8().constData());
4589         multiprod.set("video_index", video_list.at(j));
4590         QImage thumb = KThumb::getFrame(&multiprod, 0, swidth, width, 60);
4591         QGroupBox *streamFrame = new QGroupBox(i18n("Video stream %1", video_list.at(j)), content);
4592         streamFrame->setProperty("vindex", video_list.at(j));
4593         groupList << streamFrame;
4594         streamFrame->setCheckable(true);
4595         streamFrame->setChecked(true);
4596         QVBoxLayout *vh = new QVBoxLayout( streamFrame );
4597         QLabel *iconLabel = new QLabel(content);
4598         iconLabel->setPixmap(QPixmap::fromImage(thumb));
4599         vh->addWidget(iconLabel);
4600         if (audio_list.count() > 1) {
4601             QComboBox *cb = new QComboBox(content);
4602             for (int k = 0; k < audio_list.count(); k++) {
4603                 cb->addItem(i18n("Audio stream %1", audio_list.at(k)), audio_list.at(k));
4604             }
4605             comboList << cb;
4606             cb->setCurrentIndex(qMin(j, audio_list.count() - 1));
4607             vh->addWidget(cb);
4608         }
4609         vbox->addWidget(streamFrame);
4610     }
4611     if (dialog.exec() == QDialog::Accepted) {
4612         // import selected streams
4613         for (int i = 0; i < groupList.count(); i++) {
4614             if (groupList.at(i)->isChecked()) {
4615                 int vindex = groupList.at(i)->property("vindex").toInt();
4616                 int aindex = comboList.at(i)->itemData(comboList.at(i)->currentIndex()).toInt();
4617                 data.insert("video_index", QString::number(vindex));
4618                 data.insert("audio_index", QString::number(aindex));
4619                 data.insert("bypassDuplicate", "1");
4620                 emit addClip(KUrl(path), data);
4621             }
4622         }
4623     }
4624 }
4625
4626 #include "renderer.moc"
4627