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