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