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