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