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