]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Fix bug on insert space in all tracks, add context menu to remove space from track.
[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 // ffmpeg Header files
26
27 extern "C" {
28 #include <avformat.h>
29 }
30
31 #include <stdlib.h>
32
33 #include <QTimer>
34 #include <QDir>
35 #include <QApplication>
36
37 #include <KDebug>
38 #include <KStandardDirs>
39 #include <KMessageBox>
40 #include <KLocale>
41 #include <KTemporaryFile>
42
43 #include "renderer.h"
44 #include "kdenlivesettings.h"
45 #include "kthumb.h"
46 #include "definitions.h"
47
48 #include <mlt++/Mlt.h>
49
50 #if LIBAVCODEC_VERSION_MAJOR > 51 || (LIBAVCODEC_VERSION_MAJOR > 50 && LIBAVCODEC_VERSION_MINOR > 54)
51 // long_name was added in FFmpeg avcodec version 51.55
52 #define ENABLE_FFMPEG_CODEC_DESCRIPTION 1
53 #endif
54
55
56
57 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr) {
58     // detect if the producer has finished playing. Is there a better way to do it ?
59     if (self->m_isBlocked) return;
60     if (mlt_properties_get_double(MLT_FRAME_PROPERTIES(frame_ptr), "_speed") == 0.0) {
61         self->emitConsumerStopped();
62     } else {
63         self->emitFrameNumber(mlt_frame_get_position(frame_ptr));
64     }
65 }
66
67 Render::Render(const QString & rendererName, int winid, int extid, QWidget *parent): QObject(parent), m_name(rendererName), m_mltConsumer(NULL), m_mltProducer(NULL), m_mltTextProducer(NULL), m_winid(winid), m_externalwinid(extid),  m_framePosition(0), m_isBlocked(true), m_blackClip(NULL), m_isSplitView(false), m_isZoneMode(false), m_isLoopMode(false) {
68     kDebug() << "//////////  USING PROFILE: " << (char*)KdenliveSettings::current_profile().toUtf8().data();
69     refreshTimer = new QTimer(this);
70     connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
71
72     /*if (rendererName == "project") m_monitorId = 10000;
73     else m_monitorId = 10001;*/
74     osdTimer = new QTimer(this);
75     connect(osdTimer, SIGNAL(timeout()), this, SLOT(slotOsdTimeout()));
76
77     m_osdProfile =   KStandardDirs::locate("data", "kdenlive/profiles/metadata.properties");
78     buildConsumer();
79
80     Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "colour", "black");
81     m_mltProducer = producer;
82     if (m_blackClip) delete m_blackClip;
83     m_blackClip = new Mlt::Producer(*m_mltProfile , "colour", "black");
84     m_blackClip->set("id", "black");
85     m_mltConsumer->connect(*m_mltProducer);
86     m_mltProducer->set_speed(0.0);
87 }
88
89 Render::~Render() {
90     closeMlt();
91 }
92
93
94 void Render::closeMlt() {
95     delete osdTimer;
96     delete refreshTimer;
97     if (m_mltConsumer)
98         delete m_mltConsumer;
99     if (m_mltProducer)
100         delete m_mltProducer;
101     if (m_blackClip) delete m_blackClip;
102     //delete m_osdInfo;
103 }
104
105
106 void Render::buildConsumer() {
107     char *tmp;
108     tmp = decodedString(KdenliveSettings::current_profile());
109     m_mltProfile = new Mlt::Profile(tmp);
110     delete[] tmp;
111
112
113     QString videoDriver = KdenliveSettings::videodrivername();
114     if (!videoDriver.isEmpty()) {
115         if (videoDriver == "x11_noaccel") {
116             setenv("SDL_VIDEO_YUV_HWACCEL", "0", 1);
117             videoDriver = "x11";
118         } else {
119             unsetenv("SDL_VIDEO_YUV_HWACCEL");
120         }
121     }
122     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
123
124     m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview");
125     m_mltConsumer->set("resize", 1);
126     m_mltConsumer->set("window_id", m_winid);
127     m_mltConsumer->set("terminate_on_pause", 1);
128     //m_mltConsumer->set("fullscreen", 1);
129     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
130     m_mltConsumer->set("rescale", "nearest");
131
132     QString audioDevice = KdenliveSettings::audiodevicename();
133     if (!audioDevice.isEmpty()) {
134         tmp = decodedString(audioDevice);
135         m_mltConsumer->set("audio_device", tmp);
136         delete[] tmp;
137     }
138
139     if (!videoDriver.isEmpty()) {
140         tmp = decodedString(videoDriver);
141         m_mltConsumer->set("video_driver", tmp);
142         delete[] tmp;
143     }
144
145     QString audioDriver = KdenliveSettings::audiodrivername();
146     if (!audioDriver.isEmpty()) {
147         tmp = decodedString(audioDriver);
148         m_mltConsumer->set("audio_driver", tmp);
149         delete[] tmp;
150     }
151
152
153     m_mltConsumer->set("progressive", 1);
154     m_mltConsumer->set("audio_buffer", 1024);
155     m_mltConsumer->set("frequency", 48000);
156 }
157
158 int Render::resetProfile() {
159     if (!m_mltConsumer) return 0;
160     QString currentProfile = getenv("MLT_PROFILE");
161     if (currentProfile == KdenliveSettings::current_profile()) {
162         kDebug() << "reset to same profile, nothing to do";
163         return 1;
164     }
165     if (m_isSplitView) slotSplitView(false);
166     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
167     m_mltConsumer->purge();
168     delete m_mltConsumer;
169     m_mltConsumer = NULL;
170     QString scene = sceneList();
171     if (m_mltProducer) delete m_mltProducer;
172     m_mltProducer = NULL;
173     if (m_mltProfile) delete m_mltProfile;
174     m_mltProfile = NULL;
175     buildConsumer();
176
177     //kDebug() << "//RESET WITHSCENE: " << scene;
178     setSceneList(scene);
179
180     char *tmp = decodedString(scene);
181     Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "westley-xml", tmp);
182     delete[] tmp;
183     m_mltProducer = producer;
184     if (m_blackClip) delete m_blackClip;
185     m_blackClip = new Mlt::Producer(*m_mltProfile , "colour", "black");
186     m_mltProducer->optimise();
187     m_mltProducer->set_speed(0);
188     connectPlaylist();
189
190     //delete m_mltProfile;
191     // mlt_properties properties = MLT_CONSUMER_PROPERTIES(m_mltConsumer->get_consumer());
192     //mlt_profile prof = m_mltProfile->get_profile();
193     //mlt_properties_set_data(properties, "_profile", prof, 0, (mlt_destructor)mlt_profile_close, NULL);
194     //mlt_properties_set(properties, "profile", "hdv_1080_50i");
195     //m_mltConsumer->set("profile", (char *) profile.toUtf8().data());
196     //m_mltProfile = new Mlt::Profile((char*) profile.toUtf8().data());
197
198     //apply_profile_properties( m_mltProfile, m_mltConsumer->get_consumer(), properties );
199     //refresh();
200     return 1;
201 }
202
203 /** Wraps the VEML command of the same name; Seeks the renderer clip to the given time. */
204 void Render::seek(GenTime time) {
205     if (!m_mltProducer)
206         return;
207     m_isBlocked = false;
208     m_mltProducer->seek((int)(time.frames(m_fps)));
209     refresh();
210 }
211
212 //static
213 char *Render::decodedString(QString str) {
214     /*QCString fn = QFile::encodeName(str);
215     char *t = new char[fn.length() + 1];
216     strcpy(t, (const char *)fn);*/
217
218     return (char *) qstrdup(str.toUtf8().data());   //toLatin1
219 }
220
221 //static
222 /*QPixmap Render::frameThumbnail(Mlt::Frame *frame, int width, int height, bool border) {
223     QPixmap pix(width, height);
224
225     mlt_image_format format = mlt_image_rgb24a;
226     uint8_t *thumb = frame->get_image(format, width, height);
227     QImage image(thumb, width, height, QImage::Format_ARGB32);
228
229     if (!image.isNull()) {
230         pix = pix.fromImage(image);
231         if (border) {
232             QPainter painter(&pix);
233             painter.drawRect(0, 0, width - 1, height - 1);
234         }
235     } else pix.fill(Qt::black);
236     return pix;
237 }
238 */
239 const int Render::renderWidth() const {
240     return (int)(m_mltProfile->height() * m_mltProfile->dar());
241 }
242
243 const int Render::renderHeight() const {
244     return m_mltProfile->height();
245 }
246
247 QPixmap Render::extractFrame(int frame_position, int width, int height) {
248     if (width == -1) {
249         width = renderWidth();
250         height = renderHeight();
251     }
252     QPixmap pix(width, height);
253     if (!m_mltProducer) {
254         pix.fill(Qt::black);
255         return pix;
256     }
257     return KThumb::getFrame(m_mltProducer, frame_position, width, height);
258 }
259
260 QPixmap Render::getImageThumbnail(KUrl url, int width, int height) {
261     QImage im;
262     QPixmap pixmap;
263     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
264         QString fileType = url.fileName().right(3);
265         QStringList more;
266         QStringList::Iterator it;
267
268         QDir dir(url.directory());
269         QStringList filter;
270         filter << "*." + fileType;
271         filter << "*." + fileType.toUpper();
272         more = dir.entryList(filter, QDir::Files);
273         im.load(url.directory() + "/" + more.at(0));
274     } else im.load(url.path());
275     //pixmap = im.scaled(width, height);
276     return pixmap;
277 }
278 /*
279 //static
280 QPixmap Render::getVideoThumbnail(char *profile, QString file, int frame_position, int width, int height) {
281     QPixmap pix(width, height);
282     char *tmp = decodedString(file);
283     Mlt::Profile *prof = new Mlt::Profile(profile);
284     Mlt::Producer m_producer(*prof, tmp);
285     delete[] tmp;
286     if (m_producer.is_blank()) {
287         pix.fill(Qt::black);
288         return pix;
289     }
290
291     Mlt::Filter m_convert(*prof, "avcolour_space");
292     m_convert.set("forced", mlt_image_rgb24a);
293     m_producer.attach(m_convert);
294     m_producer.seek(frame_position);
295     Mlt::Frame * frame = m_producer.get_frame();
296     if (frame) {
297         pix = frameThumbnail(frame, width, height, true);
298         delete frame;
299     }
300     if (prof) delete prof;
301     return pix;
302 }
303 */
304 /*
305 void Render::getImage(KUrl url, int frame_position, QPoint size)
306 {
307     char *tmp = decodedString(url.path());
308     Mlt::Producer m_producer(tmp);
309     delete[] tmp;
310     if (m_producer.is_blank()) {
311  return;
312     }
313     Mlt::Filter m_convert("avcolour_space");
314     m_convert.set("forced", mlt_image_rgb24a);
315     m_producer.attach(m_convert);
316     m_producer.seek(frame_position);
317
318     Mlt::Frame * frame = m_producer.get_frame();
319
320     if (frame) {
321  QPixmap pix = frameThumbnail(frame, size.x(), size.y(), true);
322  delete frame;
323  emit replyGetImage(url, frame_position, pix, size.x(), size.y());
324     }
325 }*/
326
327 /* Create thumbnail for color */
328 /*void Render::getImage(int id, QString color, QPoint size)
329 {
330     QPixmap pixmap(size.x() - 2, size.y() - 2);
331     color = color.replace(0, 2, "#");
332     color = color.left(7);
333     pixmap.fill(QColor(color));
334     QPixmap result(size.x(), size.y());
335     result.fill(Qt::black);
336     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
337     emit replyGetImage(id, result, size.x(), size.y());
338
339 }*/
340
341 /* Create thumbnail for image */
342 /*void Render::getImage(KUrl url, QPoint size)
343 {
344     QImage im;
345     QPixmap pixmap;
346     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
347      QString fileType = url.fileName().right(3);
348          QStringList more;
349          QStringList::Iterator it;
350
351             QDir dir( url.directory() );
352             more = dir.entryList( QDir::Files );
353             for ( it = more.begin() ; it != more.end() ; ++it ) {
354                 if ((*it).endsWith("."+fileType, Qt::CaseInsensitive)) {
355    if (!im.load(url.directory() + "/" + *it))
356        kDebug()<<"++ ERROR LOADIN IMAGE: "<<url.directory() + "/" + *it;
357    break;
358   }
359      }
360     }
361     else im.load(url.path());
362
363     //pixmap = im.smoothScale(size.x() - 2, size.y() - 2);
364     QPixmap result(size.x(), size.y());
365     result.fill(Qt::black);
366     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
367     emit replyGetImage(url, 1, result, size.x(), size.y());
368 }*/
369
370
371 double Render::consumerRatio() const {
372     if (!m_mltConsumer) return 1.0;
373     return (m_mltConsumer->get_double("aspect_ratio_num") / m_mltConsumer->get_double("aspect_ratio_den"));
374 }
375
376
377 int Render::getLength() {
378
379     if (m_mltProducer) {
380         // kDebug()<<"//////  LENGTH: "<<mlt_producer_get_playtime(m_mltProducer->get_producer());
381         return mlt_producer_get_playtime(m_mltProducer->get_producer());
382     }
383     return 0;
384 }
385
386 bool Render::isValid(KUrl url) {
387     char *tmp = decodedString(url.path());
388     Mlt::Producer producer(*m_mltProfile, tmp);
389     delete[] tmp;
390     if (producer.is_blank())
391         return false;
392
393     return true;
394 }
395
396 const double Render::dar() const {
397     return m_mltProfile->dar();
398 }
399
400 void Render::slotSplitView(bool doit) {
401     m_isSplitView = doit;
402     Mlt::Service service(m_mltProducer->parent().get_service());
403     Mlt::Tractor tractor(service);
404     if (service.type() != tractor_type || tractor.count() < 2) return;
405     Mlt::Field *field = tractor.field();
406     if (doit) {
407         int screen = 0;
408         for (int i = 1; i < tractor.count() && screen < 4; i++) {
409             Mlt::Producer trackProducer(tractor.track(i));
410             kDebug() << "// TRACK: " << i << ", HIDE: " << trackProducer.get("hide");
411             if (QString(trackProducer.get("hide")).toInt() != 1) {
412                 kDebug() << "// ADIDNG TRACK: " << i;
413                 Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
414                 transition->set("mlt_service", "composite");
415                 transition->set("a_track", 0);
416                 transition->set("b_track", i);
417                 transition->set("distort", 1);
418                 transition->set("internal_added", "200");
419                 const char *tmp;
420                 switch (screen) {
421                 case 0:
422                     tmp = "0,0:50%x50%";
423                     break;
424                 case 1:
425                     tmp = "50%,0:50%x50%";
426                     break;
427                 case 2:
428                     tmp = "0,50%:50%x50%";
429                     break;
430                 case 3:
431                     tmp = "50%,50%:50%x50%";
432                     break;
433                 }
434                 transition->set("geometry", tmp);
435                 transition->set("always_active", "1");
436                 field->plant_transition(*transition, 0, i);
437                 //delete[] tmp;
438                 screen++;
439             }
440         }
441         m_mltConsumer->set("refresh", 1);
442     } else {
443         mlt_service serv = m_mltProducer->parent().get_service();
444         mlt_service nextservice = mlt_service_get_producer(serv);
445         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
446         QString mlt_type = mlt_properties_get(properties, "mlt_type");
447         QString resource = mlt_properties_get(properties, "mlt_service");
448
449         while (mlt_type == "transition") {
450             QString added = mlt_properties_get(MLT_SERVICE_PROPERTIES(nextservice), "internal_added");
451             if (added == "200") {
452                 mlt_field_disconnect_service(field->get_field(), nextservice);
453             }
454             nextservice = mlt_service_producer(nextservice);
455             if (nextservice == NULL) break;
456             properties = MLT_SERVICE_PROPERTIES(nextservice);
457             mlt_type = mlt_properties_get(properties, "mlt_type");
458             resource = mlt_properties_get(properties, "mlt_service");
459             m_mltConsumer->set("refresh", 1);
460         }
461     }
462 }
463
464 void Render::getFileProperties(const QDomElement &xml, const QString &clipId) {
465     int height = 50;
466     int width = (int)(height  * m_mltProfile->dar());
467     QMap < QString, QString > filePropertyMap;
468     QMap < QString, QString > metadataPropertyMap;
469
470     KUrl url = KUrl(xml.attribute("resource", QString::null));
471     Mlt::Producer *producer = NULL;
472     if (xml.attribute("type").toInt() == TEXT && !QFile::exists(url.path())) {
473         emit replyGetFileProperties(clipId, producer, filePropertyMap, metadataPropertyMap);
474         return;
475     }
476     if (xml.attribute("type").toInt() == COLOR) {
477         char *tmp = decodedString("colour:" + xml.attribute("colour"));
478         producer = new Mlt::Producer(*m_mltProfile, "fezzik", tmp);
479         delete[] tmp;
480     } else if (url.isEmpty()) {
481         QDomDocument doc;
482         QDomElement westley = doc.createElement("westley");
483         QDomElement play = doc.createElement("playlist");
484         doc.appendChild(westley);
485         westley.appendChild(play);
486         play.appendChild(doc.importNode(xml, true));
487         char *tmp = decodedString(doc.toString());
488         producer = new Mlt::Producer(*m_mltProfile, "westley-xml", tmp);
489         delete[] tmp;
490     } else {
491         QString urlpath = url.path();
492         /*if (urlpath.contains(':')) {
493             if (!urlpath.startsWith("file:")) urlpath.prepend("file:");
494             char *tmp = decodedString(urlpath);
495             producer = new Mlt::Producer(*m_mltProfile, "avformat", tmp);
496             delete[] tmp;
497         }
498         else {*/
499         char *tmp = decodedString(urlpath);
500         producer = new Mlt::Producer(*m_mltProfile, tmp);
501         delete[] tmp;
502
503         if (xml.hasAttribute("force_aspect_ratio")) {
504             double aspect = xml.attribute("force_aspect_ratio").toDouble();
505             if (aspect > 0) producer->set("force_aspect_ratio", aspect);
506         }
507         if (xml.hasAttribute("threads")) {
508             int threads = xml.attribute("threads").toInt();
509             if (threads != 1) producer->set("threads", threads);
510         }
511         if (xml.hasAttribute("video_index")) {
512             int vindex = xml.attribute("video_index").toInt();
513             if (vindex != 0) producer->set("video_index", vindex);
514         }
515         if (xml.hasAttribute("audio_index")) {
516             int aindex = xml.attribute("audio_index").toInt();
517             if (aindex != 0) producer->set("audio_index", aindex);
518         }
519         //}
520     }
521     if (xml.hasAttribute("out")) producer->set_in_and_out(xml.attribute("in").toInt(), xml.attribute("out").toInt());
522
523     if (producer->is_blank() || !producer->is_valid()) {
524         kDebug() << " / / / / / / / /ERRROR / / / / // CANNOT LOAD PRODUCER: ";
525         emit removeInvalidClip(clipId);
526         return;
527     }
528     char *tmp = decodedString(clipId);
529     producer->set("id", tmp);
530     delete[] tmp;
531     int frameNumber = xml.attribute("thumbnail", "0").toInt();
532     if (frameNumber != 0) producer->seek(frameNumber);
533     mlt_properties properties = MLT_PRODUCER_PROPERTIES(producer->get_producer());
534
535     filePropertyMap["duration"] = QString::number(producer->get_playtime());
536     //kDebug() << "///////  PRODUCER: " << url.path() << " IS: " << producer.get_playtime();
537
538     Mlt::Frame *frame = producer->get_frame();
539
540     if (xml.attribute("type").toInt() == SLIDESHOW) {
541         if (xml.hasAttribute("ttl")) producer->set("ttl", xml.attribute("ttl").toInt());
542         if (xml.attribute("fade") == "1") {
543             // user wants a fade effect to slideshow
544             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, "luma");
545             if (xml.hasAttribute("ttl")) filter->set("period", xml.attribute("ttl").toInt() - 1);
546             if (xml.hasAttribute("luma_duration") && !xml.attribute("luma_duration").isEmpty()) filter->set("luma.out", xml.attribute("luma_duration").toInt());
547             if (xml.hasAttribute("luma_file") && !xml.attribute("luma_file").isEmpty()) {
548                 char *tmp = decodedString(xml.attribute("luma_file"));
549                 filter->set("luma.resource", tmp);
550                 delete[] tmp;
551                 if (xml.hasAttribute("softness")) {
552                     int soft = xml.attribute("softness").toInt();
553                     filter->set("luma.softness", (double) soft / 100.0);
554                 }
555             }
556             Mlt::Service clipService(producer->get_service());
557             clipService.attach(*filter);
558         }
559     }
560
561
562     filePropertyMap["fps"] = producer->get("source_fps");
563
564     if (frame && frame->is_valid()) {
565         filePropertyMap["frame_size"] = QString::number(frame->get_int("width")) + "x" + QString::number(frame->get_int("height"));
566         filePropertyMap["frequency"] = QString::number(frame->get_int("frequency"));
567         filePropertyMap["channels"] = QString::number(frame->get_int("channels"));
568         filePropertyMap["aspect_ratio"] = frame->get("aspect_ratio");
569
570         if (frame->get_int("test_image") == 0) {
571             if (url.path().endsWith(".westley") || url.path().endsWith(".kdenlive")) {
572                 filePropertyMap["type"] = "playlist";
573                 metadataPropertyMap["comment"] = QString::fromUtf8(mlt_properties_get(MLT_SERVICE_PROPERTIES(producer->get_service()), "title"));
574             } else if (frame->get_int("test_audio") == 0)
575                 filePropertyMap["type"] = "av";
576             else
577                 filePropertyMap["type"] = "video";
578
579             mlt_image_format format = mlt_image_yuv422;
580             int frame_width = 0;
581             int frame_height = 0;
582             //frame->set("rescale.interp", "hyper");
583             frame->set("normalised_height", height);
584             frame->set("normalised_width", width);
585             QPixmap pix(width, height);
586
587             uint8_t *data = frame->get_image(format, frame_width, frame_height, 0);
588             uint8_t *new_image = (uint8_t *)mlt_pool_alloc(frame_width * (frame_height + 1) * 4);
589             mlt_convert_yuv422_to_rgb24a((uint8_t *)data, new_image, frame_width * frame_height);
590             QImage image((uchar *)new_image, frame_width, frame_height, QImage::Format_ARGB32);
591
592             if (!image.isNull()) {
593                 pix = QPixmap::fromImage(image.rgbSwapped());
594             } else
595                 pix.fill(Qt::black);
596
597             mlt_pool_release(new_image);
598             emit replyGetImage(clipId, 0, pix, width, height);
599
600         } else if (frame->get_int("test_audio") == 0) {
601             QPixmap pixmap = KIcon("audio-x-generic").pixmap(QSize(width, height));
602             emit replyGetImage(clipId, 0, pixmap, width, height);
603             filePropertyMap["type"] = "audio";
604         }
605     }
606
607     // Retrieve audio / video codec name
608
609     // Fetch the video_context
610 #if 1
611
612     AVFormatContext *context = (AVFormatContext *) mlt_properties_get_data(properties, "video_context", NULL);
613     if (context != NULL) {
614         /*if (context->duration == AV_NOPTS_VALUE) {
615         kDebug() << " / / / / / / / /ERRROR / / / CLIP HAS UNKNOWN DURATION";
616             emit removeInvalidClip(clipId);
617             return;
618         }*/
619         // Get the video_index
620         int index = mlt_properties_get_int(properties, "video_index");
621         int default_video = -1;
622         int video_max = 0;
623         int default_audio = -1;
624         int audio_max = 0;
625         // Find default audio stream (borrowed from MLT)
626         for (int ix = 0; ix < context->nb_streams; ix++) {
627             // Get the codec context
628             AVCodecContext *codec_context = context->streams[ ix ]->codec;
629
630             if (avcodec_find_decoder(codec_context->codec_id) == NULL)
631                 continue;
632             // Determine the type and obtain the first index of each type
633             switch (codec_context->codec_type) {
634             case CODEC_TYPE_VIDEO:
635                 if (default_video < 0) default_video = ix;
636                 video_max = ix;
637                 break;
638             case CODEC_TYPE_AUDIO:
639                 if (default_audio < 0) default_audio = ix;
640                 audio_max = ix;
641                 break;
642             default:
643                 break;
644             }
645         }
646         filePropertyMap["default_video"] = QString::number(default_video);
647         filePropertyMap["video_max"] = QString::number(video_max);
648         filePropertyMap["default_audio"] = QString::number(default_audio);
649         filePropertyMap["audio_max"] = QString::number(audio_max);
650
651
652 #if ENABLE_FFMPEG_CODEC_DESCRIPTION
653         if (index > -1 && context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->long_name) {
654             filePropertyMap["videocodec"] = context->streams[ index ]->codec->codec->long_name;
655         } else
656 #endif
657             if (index > -1 && context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->name) {
658                 filePropertyMap["videocodec"] = context->streams[ index ]->codec->codec->name;
659             }
660     } else kDebug() << " / / / / /WARNING, VIDEO CONTEXT IS NULL!!!!!!!!!!!!!!";
661     context = (AVFormatContext *) mlt_properties_get_data(properties, "audio_context", NULL);
662     if (context != NULL) {
663         // Get the audio_index
664         int index = mlt_properties_get_int(properties, "audio_index");
665
666 #if ENABLE_FFMPEG_CODEC_DESCRIPTION
667         if (index > -1 && context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->long_name)
668             filePropertyMap["audiocodec"] = context->streams[ index ]->codec->codec->long_name;
669         else
670 #endif
671             if (index > -1 && context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->name)
672                 filePropertyMap["audiocodec"] = context->streams[ index ]->codec->codec->name;
673     }
674 #endif
675     // metadata
676
677     mlt_properties metadata = mlt_properties_new();
678     mlt_properties_pass(metadata, properties, "meta.attr.");
679     int count = mlt_properties_count(metadata);
680     for (int i = 0; i < count; i ++) {
681         QString name = mlt_properties_get_name(metadata, i);
682         QString value = QString::fromUtf8(mlt_properties_get_value(metadata, i));
683         if (name.endsWith("markup") && !value.isEmpty())
684             metadataPropertyMap[ name.section(".", 0, -2)] = value;
685     }
686
687     emit replyGetFileProperties(clipId, producer, filePropertyMap, metadataPropertyMap);
688     kDebug() << "REquested fuile info for: " << url.path();
689     if (frame) delete frame;
690     //if (producer) delete producer;
691 }
692
693
694 /** Create the producer from the Westley QDomDocument */
695 #if 0
696 void Render::initSceneList() {
697     kDebug() << "--------  INIT SCENE LIST ------_";
698     QDomDocument doc;
699     QDomElement westley = doc.createElement("westley");
700     doc.appendChild(westley);
701     QDomElement prod = doc.createElement("producer");
702     prod.setAttribute("resource", "colour");
703     prod.setAttribute("colour", "red");
704     prod.setAttribute("id", "black");
705     prod.setAttribute("in", "0");
706     prod.setAttribute("out", "0");
707
708     QDomElement tractor = doc.createElement("tractor");
709     QDomElement multitrack = doc.createElement("multitrack");
710
711     QDomElement playlist1 = doc.createElement("playlist");
712     playlist1.appendChild(prod);
713     multitrack.appendChild(playlist1);
714     QDomElement playlist2 = doc.createElement("playlist");
715     multitrack.appendChild(playlist2);
716     QDomElement playlist3 = doc.createElement("playlist");
717     multitrack.appendChild(playlist3);
718     QDomElement playlist4 = doc.createElement("playlist");
719     multitrack.appendChild(playlist4);
720     QDomElement playlist5 = doc.createElement("playlist");
721     multitrack.appendChild(playlist5);
722     tractor.appendChild(multitrack);
723     westley.appendChild(tractor);
724     // kDebug()<<doc.toString();
725     /*
726        QString tmp = QString("<westley><producer resource=\"colour\" colour=\"red\" id=\"red\" /><tractor><multitrack><playlist></playlist><playlist></playlist><playlist /><playlist /><playlist></playlist></multitrack></tractor></westley>");*/
727     setSceneList(doc, 0);
728 }
729 #endif
730
731
732
733 /** Create the producer from the Westley QDomDocument */
734 void Render::setProducer(Mlt::Producer *producer, int position) {
735     if (m_winid == -1) return;
736
737     if (m_mltConsumer) {
738         m_mltConsumer->stop();
739     } else return;
740
741     m_isBlocked = true;
742     if (m_mltProducer) {
743         m_mltProducer->set_speed(0);
744         delete m_mltProducer;
745         m_mltProducer = NULL;
746         emit stopped();
747     }
748     if (producer) m_mltProducer = new Mlt::Producer(producer->get_producer());
749     else m_mltProducer = new Mlt::Producer();
750     if (!m_mltProducer || !m_mltProducer->is_valid()) kDebug() << " WARNING - - - - -INVALID PLAYLIST: ";
751
752     m_fps = m_mltProducer->get_fps();
753     connectPlaylist();
754     if (position != -1) {
755         m_mltProducer->seek(position);
756         emit rendererPosition(position);
757     }
758     m_isBlocked = false;
759 }
760
761
762
763 /** Create the producer from the Westley QDomDocument */
764 void Render::setSceneList(QDomDocument list, int position) {
765     setSceneList(list.toString(), position);
766 }
767
768 /** Create the producer from the Westley QDomDocument */
769 void Render::setSceneList(QString playlist, int position) {
770     if (m_winid == -1) return;
771     m_isBlocked = true;
772
773     //kWarning() << "//////  RENDER, SET SCENE LIST: " << playlist;
774
775     if (m_mltConsumer) {
776         m_mltConsumer->stop();
777         //m_mltConsumer->set("refresh", 0);
778     } else return;
779
780     if (m_mltProducer) {
781         m_mltProducer->set_speed(0);
782         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
783
784         delete m_mltProducer;
785         m_mltProducer = NULL;
786         emit stopped();
787     }
788
789     char *tmp = decodedString(playlist);
790     m_mltProducer = new Mlt::Producer(*m_mltProfile, "westley-xml", tmp);
791     delete[] tmp;
792     if (m_blackClip) delete m_blackClip;
793     m_blackClip = new Mlt::Producer(*m_mltProfile , "colour", "black");
794     m_blackClip->set("id", "black");
795     if (!m_mltProducer || !m_mltProducer->is_valid()) {
796         kDebug() << " WARNING - - - - -INVALID PLAYLIST: " << tmp;
797     }
798     m_mltProducer->optimise();
799
800     /*if (KdenliveSettings::osdtimecode()) {
801     // Attach filter for on screen display of timecode
802     delete m_osdInfo;
803     QString attr = "attr_check";
804     mlt_filter filter = mlt_factory_filter( "data_feed", (char*) attr.ascii() );
805     mlt_properties_set_int( MLT_FILTER_PROPERTIES( filter ), "_fezzik", 1 );
806     mlt_producer_attach( m_mltProducer->get_producer(), filter );
807     mlt_filter_close( filter );
808
809       m_osdInfo = new Mlt::Filter("data_show");
810     tmp = decodedString(m_osdProfile);
811       m_osdInfo->set("resource", tmp);
812     delete[] tmp;
813     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
814     mlt_properties_set_int( properties, "meta.attr.timecode", 1);
815     mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
816     m_osdInfo->set("dynamic", "1");
817
818       if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
819     } else {
820     m_osdInfo->set("dynamic", "0");
821     }*/
822
823     m_fps = m_mltProducer->get_fps();
824     kDebug() << "// NEW SCENE LIST DURATION SET TO: " << m_mltProducer->get_playtime();
825     connectPlaylist();
826     if (position != 0) {
827         //TODO: seek to correct place after opening project.
828         //  Needs to be done from another place since it crashes here.
829         //m_mltProducer->seek(position);
830         //emit rendererPosition(position);
831     }
832     m_isBlocked = false;
833
834 }
835
836 /** Create the producer from the Westley QDomDocument */
837 QString Render::sceneList() {
838     QString playlist;
839     Mlt::Consumer westleyConsumer(*m_mltProfile , "westley:kdenlive_playlist");
840     m_mltProducer->optimise();
841     westleyConsumer.set("terminate_on_pause", 1);
842     Mlt::Producer prod(m_mltProducer->get_producer());
843     bool split = m_isSplitView;
844     if (split) slotSplitView(false);
845     westleyConsumer.connect(prod);
846     westleyConsumer.start();
847     while (!westleyConsumer.is_stopped()) {}
848     playlist = QString::fromUtf8(westleyConsumer.get("kdenlive_playlist"));
849     if (split) slotSplitView(true);
850     return playlist;
851 }
852
853 void Render::saveSceneList(QString path, QDomElement kdenliveData) {
854     QFile file(path);
855     QDomDocument doc;
856     doc.setContent(sceneList(), false);
857     if (!kdenliveData.isNull()) {
858         // add Kdenlive specific tags
859         QDomNode wes = doc.elementsByTagName("westley").at(0);
860         wes.appendChild(doc.importNode(kdenliveData, true));
861     }
862     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
863         kWarning() << "//////  ERROR writing to file: " << path;
864         return;
865     }
866     QTextStream out(&file);
867     out << doc.toString();
868     file.close();
869 }
870
871
872 void Render::saveZone(KUrl url, QString desc, QPoint zone) {
873     kDebug() << "// SAVING CLIP ZONE, RENDER: " << m_name;
874     char *tmppath = decodedString("westley:" + url.path());
875     Mlt::Consumer westleyConsumer(*m_mltProfile , tmppath);
876     m_mltProducer->optimise();
877     delete[] tmppath;
878     westleyConsumer.set("terminate_on_pause", 1);
879     if (m_name == "clip") {
880         Mlt::Producer *prod = m_mltProducer->cut(zone.x(), zone.y());
881         tmppath = decodedString(desc);
882         Mlt::Playlist list;
883         list.insert_at(0, prod, 0);
884         list.set("title", tmppath);
885         delete[] tmppath;
886         westleyConsumer.connect(list);
887
888     } else {
889         //TODO: not working yet, save zone from timeline
890         Mlt::Producer *p1 = new Mlt::Producer(m_mltProducer->get_producer());
891         /* Mlt::Service service(p1->parent().get_service());
892          if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";*/
893
894         //Mlt::Producer *prod = p1->cut(zone.x(), zone.y());
895         tmppath = decodedString(desc);
896         //prod->set("title", tmppath);
897         delete[] tmppath;
898         westleyConsumer.connect(*p1); //list);
899     }
900
901     westleyConsumer.start();
902 }
903
904 const double Render::fps() const {
905     return m_fps;
906 }
907
908 void Render::connectPlaylist() {
909     if (!m_mltConsumer) return;
910     //m_mltConsumer->set("refresh", "0");
911     m_mltConsumer->connect(*m_mltProducer);
912     m_mltProducer->set_speed(0);
913     m_mltConsumer->start();
914     emit durationChanged(m_mltProducer->get_playtime());
915     //refresh();
916     /*
917      if (m_mltConsumer->start() == -1) {
918           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."));
919           m_mltConsumer = NULL;
920      }
921      else {
922              refresh();
923      }*/
924 }
925
926 void Render::refreshDisplay() {
927
928     if (!m_mltProducer) return;
929     //m_mltConsumer->set("refresh", 0);
930
931     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
932     /*if (KdenliveSettings::osdtimecode()) {
933         mlt_properties_set_int( properties, "meta.attr.timecode", 1);
934         mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
935         m_osdInfo->set("dynamic", "1");
936         m_mltProducer->attach(*m_osdInfo);
937     }
938     else {
939         m_mltProducer->detach(*m_osdInfo);
940         m_osdInfo->set("dynamic", "0");
941     }*/
942     refresh();
943 }
944
945 void Render::setVolume(double volume) {
946     if (!m_mltConsumer || !m_mltProducer) return;
947     /*osdTimer->stop();
948     m_mltConsumer->set("refresh", 0);
949     // Attach filter for on screen display of timecode
950     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
951     mlt_properties_set_double( properties, "meta.volume", volume );
952     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
953     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
954
955     if (!KdenliveSettings::osdtimecode()) {
956     m_mltProducer->detach(*m_osdInfo);
957     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
958      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
959     }*/
960     refresh();
961     osdTimer->setSingleShot(2500);
962 }
963
964 void Render::slotOsdTimeout() {
965     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
966     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
967     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
968     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
969     refresh();
970 }
971
972 void Render::start() {
973     kDebug() << "-----  STARTING MONITOR: " << m_name;
974     if (m_winid == -1) {
975         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
976         return;
977     }
978
979     if (m_mltConsumer && m_mltConsumer->is_stopped()) {
980         kDebug() << "-----  MONITOR: " << m_name << " WAS STOPPED";
981         if (m_mltConsumer->start() == -1) {
982             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."));
983             m_mltConsumer = NULL;
984             return;
985         } else {
986             kDebug() << "-----  MONITOR: " << m_name << " REFRESH";
987             m_isBlocked = false;
988             refresh();
989         }
990     }
991     m_isBlocked = false;
992 }
993
994 void Render::clear() {
995     kDebug() << " *********  RENDER CLEAR";
996     if (m_mltConsumer) {
997         //m_mltConsumer->set("refresh", 0);
998         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
999     }
1000
1001     if (m_mltProducer) {
1002         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
1003         m_mltProducer->set_speed(0.0);
1004         delete m_mltProducer;
1005         m_mltProducer = NULL;
1006         emit stopped();
1007     }
1008 }
1009
1010 void Render::stop() {
1011     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
1012         kDebug() << "/////////////   RENDER STOPPED: " << m_name;
1013         m_isBlocked = true;
1014         m_mltConsumer->set("refresh", 0);
1015         m_mltConsumer->stop();
1016         // delete m_mltConsumer;
1017         // m_mltConsumer = NULL;
1018     }
1019     kDebug() << "/////////////   RENDER STOP2-------";
1020     m_isBlocked = true;
1021
1022     if (m_mltProducer) {
1023         if (m_isZoneMode) resetZoneMode();
1024         m_mltProducer->set_speed(0.0);
1025         //m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1026         //kDebug() << m_mltProducer->get_length();
1027     }
1028     kDebug() << "/////////////   RENDER STOP3-------";
1029 }
1030
1031 void Render::stop(const GenTime & startTime) {
1032
1033     kDebug() << "/////////////   RENDER STOP-------2";
1034     if (m_mltProducer) {
1035         if (m_isZoneMode) resetZoneMode();
1036         m_mltProducer->set_speed(0.0);
1037         m_mltProducer->seek((int) startTime.frames(m_fps));
1038     }
1039     m_mltConsumer->purge();
1040 }
1041
1042 void Render::pause() {
1043     if (!m_mltProducer || !m_mltConsumer)
1044         return;
1045     if (m_mltProducer->get_speed() == 0.0) return;
1046     if (m_isZoneMode) resetZoneMode();
1047     m_isBlocked = true;
1048     m_mltConsumer->set("refresh", 0);
1049     m_mltProducer->set_speed(0.0);
1050     emit rendererPosition(m_framePosition);
1051     m_mltProducer->seek(m_framePosition);
1052     m_mltConsumer->purge();
1053 }
1054
1055 void Render::switchPlay() {
1056     if (!m_mltProducer || !m_mltConsumer)
1057         return;
1058     if (m_isZoneMode) resetZoneMode();
1059     if (m_mltProducer->get_speed() == 0.0) {
1060         m_isBlocked = false;
1061         m_mltProducer->set_speed(1.0);
1062         m_mltConsumer->set("refresh", 1);
1063     } else {
1064         m_isBlocked = true;
1065         m_mltConsumer->set("refresh", 0);
1066         m_mltProducer->set_speed(0.0);
1067         emit rendererPosition(m_framePosition);
1068         m_mltProducer->seek(m_framePosition);
1069         m_mltConsumer->purge();
1070         //kDebug()<<" *********  RENDER PAUSE: "<<m_mltProducer->get_speed();
1071         //m_mltConsumer->set("refresh", 0);
1072         /*mlt_position position = mlt_producer_position( m_mltProducer->get_producer() );
1073         m_mltProducer->set_speed(0);
1074         m_mltProducer->seek( position );
1075                //m_mltProducer->seek((int) m_framePosition);
1076                m_isBlocked = false;*/
1077     }
1078     /*if (speed == 0.0) {
1079     m_mltProducer->seek((int) m_framePosition + 1);
1080         m_mltConsumer->purge();
1081     }*/
1082     //refresh();
1083 }
1084
1085 void Render::play(double speed) {
1086     if (!m_mltProducer)
1087         return;
1088     // if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1089     m_isBlocked = false;
1090     m_mltProducer->set_speed(speed);
1091     /*if (speed == 0.0) {
1092     m_mltProducer->seek((int) m_framePosition + 1);
1093         m_mltConsumer->purge();
1094     }*/
1095     refresh();
1096 }
1097
1098 void Render::play(const GenTime & startTime) {
1099     if (!m_mltProducer || !m_mltConsumer)
1100         return;
1101     m_isBlocked = false;
1102     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1103     m_mltProducer->set_speed(1.0);
1104     m_mltConsumer->set("refresh", 1);
1105 }
1106
1107 void Render::loopZone(const GenTime & startTime, const GenTime & stopTime) {
1108     if (!m_mltProducer || !m_mltConsumer)
1109         return;
1110     //m_mltProducer->set("eof", "loop");
1111     m_isLoopMode = true;
1112     m_loopStart = startTime;
1113     playZone(startTime, stopTime);
1114 }
1115
1116 void Render::playZone(const GenTime & startTime, const GenTime & stopTime) {
1117     if (!m_mltProducer || !m_mltConsumer)
1118         return;
1119     m_isBlocked = false;
1120     m_mltProducer->set("out", stopTime.frames(m_fps));
1121     m_mltProducer->seek((int)(startTime.frames(m_fps)));
1122     m_mltProducer->set_speed(1.0);
1123     m_mltConsumer->set("refresh", 1);
1124     m_isZoneMode = true;
1125 }
1126
1127 void Render::resetZoneMode() {
1128     m_mltProducer->set("out", m_mltProducer->get_length() - 1);
1129     //m_mltProducer->set("eof", "pause");
1130     m_isZoneMode = false;
1131     m_isLoopMode = false;
1132 }
1133
1134 void Render::seekToFrame(int pos) {
1135     //kDebug()<<" *********  RENDER SEEK TO POS";
1136     if (!m_mltProducer)
1137         return;
1138     m_isBlocked = false;
1139     resetZoneMode();
1140     m_mltProducer->seek(pos);
1141     refresh();
1142 }
1143
1144 void Render::askForRefresh() {
1145     // Use a Timer so that we don't refresh too much
1146     refreshTimer->start(200);
1147 }
1148
1149 void Render::doRefresh() {
1150     // Use a Timer so that we don't refresh too much
1151     if (!m_isBlocked && m_mltConsumer) m_mltConsumer->set("refresh", 1);
1152 }
1153
1154 void Render::refresh() {
1155     if (!m_mltProducer || m_isBlocked)
1156         return;
1157     refreshTimer->stop();
1158     if (m_mltConsumer) {
1159         m_mltConsumer->set("refresh", 1);
1160     }
1161 }
1162
1163 double Render::playSpeed() {
1164     if (m_mltProducer) return m_mltProducer->get_speed();
1165     return 0.0;
1166 }
1167
1168 GenTime Render::seekPosition() const {
1169     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
1170     else return GenTime();
1171 }
1172
1173
1174 const QString & Render::rendererName() const {
1175     return m_name;
1176 }
1177
1178
1179 void Render::emitFrameNumber(double position) {
1180     m_framePosition = position;
1181     emit rendererPosition((int) position);
1182     //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent( GenTime((int) position, m_fps), m_monitorId));
1183 }
1184
1185 void Render::emitConsumerStopped() {
1186     // This is used to know when the playing stopped
1187     if (m_mltProducer) {
1188         double pos = m_mltProducer->position();
1189         if (m_isLoopMode) play(m_loopStart);
1190         else if (m_isZoneMode) resetZoneMode();
1191         emit rendererStopped((int) pos);
1192         //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent(GenTime((int) pos, m_fps), m_monitorId + 100));
1193         //new QCustomEvent(10002));
1194     }
1195 }
1196
1197
1198
1199 void Render::exportFileToFirewire(QString srcFileName, int port, GenTime startTime, GenTime endTime) {
1200     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
1201 }
1202
1203
1204 void Render::exportCurrentFrame(KUrl url, bool notify) {
1205     if (!m_mltProducer) {
1206         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
1207         return;
1208     }
1209
1210     int height = 1080;//KdenliveSettings::defaultheight();
1211     int width = 1940; //KdenliveSettings::displaywidth();
1212     //TODO: rewrite
1213     QPixmap pix; // = KThumb::getFrame(m_mltProducer, -1, width, height);
1214     /*
1215        QPixmap pix(width, height);
1216        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
1217        m_convert.set("forced", mlt_image_rgb24a);
1218        m_mltProducer->attach(m_convert);
1219        Mlt::Frame * frame = m_mltProducer->get_frame();
1220        m_mltProducer->detach(m_convert);
1221        if (frame) {
1222            pix = frameThumbnail(frame, width, height);
1223            delete frame;
1224        }*/
1225     pix.save(url.path(), "PNG");
1226     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
1227 }
1228
1229 /** MLT PLAYLIST DIRECT MANIPULATON  **/
1230
1231
1232 void Render::mltCheckLength(bool reload) {
1233     //kDebug()<<"checking track length: "<<track<<"..........";
1234
1235     Mlt::Service service(m_mltProducer->get_service());
1236     Mlt::Tractor tractor(service);
1237
1238     int trackNb = tractor.count();
1239     double duration = 0;
1240     double trackDuration;
1241     if (trackNb == 1) {
1242         Mlt::Producer trackProducer(tractor.track(0));
1243         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1244         duration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
1245         m_mltProducer->set("out", duration);
1246         emit durationChanged((int) duration);
1247         return;
1248     }
1249     while (trackNb > 1) {
1250         Mlt::Producer trackProducer(tractor.track(trackNb - 1));
1251         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1252         trackDuration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
1253
1254         //kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
1255         if (trackDuration > duration) duration = trackDuration;
1256         trackNb--;
1257     }
1258
1259     Mlt::Producer blackTrackProducer(tractor.track(0));
1260     Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
1261     double blackDuration = Mlt::Producer(blackTrackPlaylist.get_producer()).get_playtime() - 1;
1262
1263     if (blackDuration != duration) {
1264         blackTrackPlaylist.remove_region(0, (int)blackDuration);
1265         int i = 0;
1266         int dur = (int)duration;
1267         QDomDocument doc;
1268         QDomElement black = doc.createElement("producer");
1269         black.setAttribute("mlt_service", "colour");
1270         black.setAttribute("colour", "black");
1271         black.setAttribute("id", "black");
1272         ItemInfo info;
1273         info.track = 0;
1274         while (dur > 14000) {
1275             info.startPos = GenTime(i * 14000, m_fps);
1276             info.endPos = info.startPos + GenTime(13999, m_fps);
1277             mltInsertClip(info, black, m_blackClip);
1278             dur = dur - 14000;
1279             i++;
1280         }
1281         if (dur > 0) {
1282             info.startPos = GenTime(i * 14000, m_fps);
1283             info.endPos = info.startPos + GenTime(dur, m_fps);
1284             mltInsertClip(info, black, m_blackClip);
1285         }
1286         m_mltProducer->set("out", duration);
1287         emit durationChanged((int)duration);
1288     }
1289 }
1290
1291 void Render::mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod) {
1292     if (!m_mltProducer) {
1293         kDebug() << "PLAYLIST NOT INITIALISED //////";
1294         return;
1295     }
1296     Mlt::Producer parentProd(m_mltProducer->parent());
1297     if (parentProd.get_producer() == NULL) {
1298         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1299         return;
1300     }
1301
1302     Mlt::Service service(parentProd.get_service());
1303     Mlt::Tractor tractor(service);
1304     mlt_service_lock(service.get_service());
1305     Mlt::Producer trackProducer(tractor.track(info.track));
1306     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1307     //kDebug()<<"/// INSERT cLIP: "<<info.cropStart.frames(m_fps)<<", "<<info.startPos.frames(m_fps)<<"-"<<info.endPos.frames(m_fps);
1308     Mlt::Producer *clip = prod->cut((int) info.cropStart.frames(m_fps), (int)(info.endPos - info.startPos + info.cropStart).frames(m_fps) - 1);
1309     int newIndex = trackPlaylist.insert_at((int) info.startPos.frames(m_fps), *clip, 1);
1310
1311     /*if (QString(prod->get("transparency")).toInt() == 1)
1312         mltAddClipTransparency(info, info.track - 1, QString(prod->get("id")).toInt());*/
1313
1314     mlt_service_unlock(service.get_service());
1315
1316     if (info.track != 0 && (newIndex + 1 == trackPlaylist.count())) mltCheckLength();
1317     //tractor.multitrack()->refresh();
1318     //tractor.refresh();
1319 }
1320
1321
1322 void Render::mltCutClip(int track, GenTime position) {
1323
1324     m_isBlocked = true;
1325
1326     Mlt::Service service(m_mltProducer->parent().get_service());
1327     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1328
1329     Mlt::Tractor tractor(service);
1330     Mlt::Producer trackProducer(tractor.track(track));
1331     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1332
1333
1334     /* // Display playlist info
1335     kDebug()<<"////////////  BEFORE";
1336     for (int i = 0; i < trackPlaylist.count(); i++) {
1337     int blankStart = trackPlaylist.clip_start(i);
1338     int blankDuration = trackPlaylist.clip_length(i) - 1;
1339     QString blk;
1340     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1341     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<"x"<<blankStart + blankDuration<<")"<<blk;
1342     }*/
1343
1344     int cutPos = (int) position.frames(m_fps);
1345
1346     int clipIndex = trackPlaylist.get_clip_index_at(cutPos);
1347     if (trackPlaylist.is_blank(clipIndex)) {
1348         kDebug() << "// WARNING, TRYING TO CUT A BLANK";
1349         m_isBlocked = false;
1350         return;
1351     }
1352     mlt_service_lock(service.get_service());
1353     int clipStart = trackPlaylist.clip_start(clipIndex);
1354     trackPlaylist.split(clipIndex, cutPos - clipStart - 1);
1355     mlt_service_unlock(service.get_service());
1356
1357     // duplicate effects
1358     Mlt::Producer *original = trackPlaylist.get_clip_at(clipStart);
1359     Mlt::Producer *clip = trackPlaylist.get_clip_at(cutPos);
1360
1361     if (original == NULL || clip == NULL) {
1362         kDebug() << "// ERROR GRABBING CLIP AFTER SPLIT";
1363     }
1364     Mlt::Service clipService(original->get_service());
1365     Mlt::Service dupService(clip->get_service());
1366     int ct = 0;
1367     Mlt::Filter *filter = clipService.filter(ct);
1368     while (filter) {
1369         if (filter->get("kdenlive_id") != "") {
1370             // looks like there is no easy way to duplicate a filter,
1371             // so we will create a new one and duplicate its properties
1372             Mlt::Filter *dup = new Mlt::Filter(*m_mltProfile, filter->get("mlt_service"));
1373             Mlt::Properties entries(filter->get_properties());
1374             for (int i = 0;i < entries.count();i++) {
1375                 dup->set(entries.get_name(i), entries.get(i));
1376             }
1377             dupService.attach(*dup);
1378         }
1379         ct++;
1380         filter = clipService.filter(ct);
1381     }
1382
1383     /* // Display playlist info
1384     kDebug()<<"////////////  AFTER";
1385     for (int i = 0; i < trackPlaylist.count(); i++) {
1386     int blankStart = trackPlaylist.clip_start(i);
1387     int blankDuration = trackPlaylist.clip_length(i) - 1;
1388     QString blk;
1389     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1390     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<"x"<<blankStart + blankDuration<<")"<<blk;
1391     }*/
1392
1393     m_isBlocked = false;
1394 }
1395
1396 void Render::mltUpdateClip(ItemInfo info, QDomElement element, Mlt::Producer *prod) {
1397     // TODO: optimize
1398     mltRemoveClip(info.track, info.startPos);
1399     mltInsertClip(info, element, prod);
1400 }
1401
1402
1403 bool Render::mltRemoveClip(int track, GenTime position) {
1404     Mlt::Service service(m_mltProducer->parent().get_service());
1405     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1406
1407     Mlt::Tractor tractor(service);
1408     Mlt::Producer trackProducer(tractor.track(track));
1409     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1410     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
1411
1412     /* // Display playlist info
1413     kDebug()<<"////  BEFORE";
1414     for (int i = 0; i < trackPlaylist.count(); i++) {
1415     int blankStart = trackPlaylist.clip_start(i);
1416     int blankDuration = trackPlaylist.clip_length(i) - 1;
1417     QString blk;
1418     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1419     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<"x"<<blankStart + blankDuration<<")"<<blk;
1420     }*/
1421
1422     if (trackPlaylist.is_blank(clipIndex)) {
1423         kDebug() << "// WARMNING, TRYING TO REMOVE A BLANK: " << clipIndex << ", AT: " << position.frames(25);
1424         return false;
1425     }
1426     m_isBlocked = true;
1427     Mlt::Producer clip(trackPlaylist.get_clip(clipIndex));
1428     trackPlaylist.replace_with_blank(clipIndex);
1429     trackPlaylist.consolidate_blanks(0);
1430     /*if (QString(clip.parent().get("transparency")).toInt() == 1)
1431         mltDeleteTransparency((int) position.frames(m_fps), track, QString(clip.parent().get("id")).toInt());*/
1432
1433     /* // Display playlist info
1434     kDebug()<<"////  AFTER";
1435     for (int i = 0; i < trackPlaylist.count(); i++) {
1436     int blankStart = trackPlaylist.clip_start(i);
1437     int blankDuration = trackPlaylist.clip_length(i) - 1;
1438     QString blk;
1439     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1440     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<"x"<<blankStart + blankDuration<<")"<<blk;
1441     }*/
1442
1443     if (track != 0 && trackPlaylist.count() > clipIndex) mltCheckLength();
1444     m_isBlocked = false;
1445     return true;
1446 }
1447
1448 int Render::mltGetSpaceLength(const GenTime pos, int track) {
1449     if (!m_mltProducer) {
1450         kDebug() << "PLAYLIST NOT INITIALISED //////";
1451         return -1;
1452     }
1453     Mlt::Producer parentProd(m_mltProducer->parent());
1454     if (parentProd.get_producer() == NULL) {
1455         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1456         return -1;
1457     }
1458
1459     Mlt::Service service(parentProd.get_service());
1460     Mlt::Tractor tractor(service);
1461     int insertPos = pos.frames(m_fps);
1462
1463     Mlt::Producer trackProducer(tractor.track(track));
1464     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1465     int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1466     if (!trackPlaylist.is_blank_at(clipIndex)) return -1;
1467     return trackPlaylist.clip_length(clipIndex);
1468 }
1469
1470
1471 void Render::mltInsertSpace(const GenTime pos, int track, const GenTime duration) {
1472     if (!m_mltProducer) {
1473         kDebug() << "PLAYLIST NOT INITIALISED //////";
1474         return;
1475     }
1476     Mlt::Producer parentProd(m_mltProducer->parent());
1477     if (parentProd.get_producer() == NULL) {
1478         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1479         return;
1480     }
1481
1482     Mlt::Service service(parentProd.get_service());
1483     Mlt::Tractor tractor(service);
1484     mlt_service_lock(service.get_service());
1485     int insertPos = pos.frames(m_fps);
1486     int diff = duration.frames(m_fps);
1487
1488     if (track != -1) {
1489         // insert space in one track only
1490         Mlt::Producer trackProducer(tractor.track(track));
1491         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1492         int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1493         if (diff > 0) trackPlaylist.insert_blank(clipIndex, diff - 1);
1494         else {
1495             int position = trackPlaylist.clip_start(clipIndex);
1496             trackPlaylist.remove_region(position, -diff - 1);
1497         }
1498         trackPlaylist.consolidate_blanks(0);
1499
1500         // now move transitions
1501         mlt_service serv = m_mltProducer->parent().get_service();
1502         mlt_service nextservice = mlt_service_get_producer(serv);
1503         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1504         QString mlt_type = mlt_properties_get(properties, "mlt_type");
1505         QString resource = mlt_properties_get(properties, "mlt_service");
1506
1507         while (mlt_type == "transition") {
1508             mlt_transition tr = (mlt_transition) nextservice;
1509             int currentTrack = mlt_transition_get_b_track(tr);
1510             int currentIn = (int) mlt_transition_get_in(tr);
1511             int currentOut = (int) mlt_transition_get_out(tr);
1512
1513             if (track == currentTrack && currentOut > insertPos && resource != "mix") {
1514                 mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
1515             }
1516             nextservice = mlt_service_producer(nextservice);
1517             if (nextservice == NULL) break;
1518             properties = MLT_SERVICE_PROPERTIES(nextservice);
1519             mlt_type = mlt_properties_get(properties, "mlt_type");
1520             resource = mlt_properties_get(properties, "mlt_service");
1521         }
1522     } else {
1523         int trackNb = tractor.count();
1524         while (trackNb > 1) {
1525             Mlt::Producer trackProducer(tractor.track(trackNb - 1));
1526             Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1527             int clipIndex = trackPlaylist.get_clip_index_at(insertPos);
1528             if (diff > 0) trackPlaylist.insert_blank(clipIndex, diff - 1);
1529             else {
1530                 int position = trackPlaylist.clip_start(clipIndex);
1531                 trackPlaylist.remove_region(position, -diff - 1);
1532             }
1533             trackPlaylist.consolidate_blanks(0);
1534             trackNb--;
1535         }
1536         // now move transitions
1537         mlt_service serv = m_mltProducer->parent().get_service();
1538         mlt_service nextservice = mlt_service_get_producer(serv);
1539         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1540         QString mlt_type = mlt_properties_get(properties, "mlt_type");
1541         QString resource = mlt_properties_get(properties, "mlt_service");
1542
1543         while (mlt_type == "transition") {
1544             mlt_transition tr = (mlt_transition) nextservice;
1545             int currentIn = (int) mlt_transition_get_in(tr);
1546             int currentOut = (int) mlt_transition_get_out(tr);
1547
1548             if (currentOut > insertPos && resource != "mix") {
1549                 mlt_transition_set_in_and_out(tr, currentIn + diff, currentOut + diff);
1550             }
1551             nextservice = mlt_service_producer(nextservice);
1552             if (nextservice == NULL) break;
1553             properties = MLT_SERVICE_PROPERTIES(nextservice);
1554             mlt_type = mlt_properties_get(properties, "mlt_type");
1555             resource = mlt_properties_get(properties, "mlt_service");
1556         }
1557     }
1558     mlt_service_unlock(service.get_service());
1559 }
1560
1561 int Render::mltChangeClipSpeed(ItemInfo info, double speed, double oldspeed, Mlt::Producer *prod) {
1562     m_isBlocked = true;
1563     int newLength = 0;
1564     Mlt::Service service(m_mltProducer->parent().get_service());
1565     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1566     kDebug() << "Changing clip speed, set in and out: " << info.cropStart.frames(m_fps) << " to " << (info.endPos - info.startPos).frames(m_fps) - 1;
1567     Mlt::Tractor tractor(service);
1568     Mlt::Producer trackProducer(tractor.track(info.track));
1569     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1570     int startPos = info.startPos.frames(m_fps);
1571     int clipIndex = trackPlaylist.get_clip_index_at(startPos);
1572     int clipLength = trackPlaylist.clip_length(clipIndex);
1573
1574     Mlt::Producer clip(trackPlaylist.get_clip(clipIndex));
1575     QString serv = clip.parent().get("mlt_service");
1576     QString id = clip.parent().get("id");
1577     kDebug() << "CLIP SERVICE: " << clip.parent().get("mlt_service");
1578     if (serv == "avformat" && speed != 1.0) {
1579         mlt_service_lock(service.get_service());
1580         QString url = clip.parent().get("resource");
1581         url.append("?" + QString::number(speed));
1582         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1583         if (!slowprod || slowprod->get_producer() == NULL) {
1584             char *tmp = decodedString(url);
1585             slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
1586             delete[] tmp;
1587             QString producerid = "slowmotion:" + id + ":" + QString::number(speed);
1588             tmp = decodedString(producerid);
1589             slowprod->set("id", tmp);
1590             delete[] tmp;
1591             m_slowmotionProducers.insert(url, slowprod);
1592         }
1593         trackPlaylist.replace_with_blank(clipIndex);
1594         trackPlaylist.consolidate_blanks(0);
1595         // Check that the blank space is long enough for our new duration
1596         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1597         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
1598         Mlt::Producer *cut;
1599         if (clipIndex + 1 < trackPlaylist.count() && (startPos + clipLength / speed > blankEnd)) {
1600             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
1601             cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)(info.cropStart.frames(m_fps) / speed + maxLength.frames(m_fps) - 1));
1602         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart.frames(m_fps) + clipLength) / speed - 1));
1603         trackPlaylist.insert_at(startPos, *cut, 1);
1604         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1605         newLength = trackPlaylist.clip_length(clipIndex);
1606         mlt_service_unlock(service.get_service());
1607     } else if (speed == 1.0) {
1608         mlt_service_lock(service.get_service());
1609
1610         trackPlaylist.replace_with_blank(clipIndex);
1611         trackPlaylist.consolidate_blanks(0);
1612
1613         // Check that the blank space is long enough for our new duration
1614         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1615         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
1616
1617         Mlt::Producer *cut;
1618         GenTime oldDuration = GenTime(clipLength, m_fps);
1619         GenTime newDuration = oldDuration * oldspeed;
1620         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + newDuration).frames(m_fps) > blankEnd) {
1621             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
1622             cut = prod->cut((int)(info.cropStart.frames(m_fps)), (int)(info.cropStart.frames(m_fps) + maxLength.frames(m_fps) - 1));
1623         } else cut = prod->cut((int)(info.cropStart.frames(m_fps)), (int)((info.cropStart + newDuration).frames(m_fps)) - 1);
1624         trackPlaylist.insert_at(startPos, *cut, 1);
1625         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1626         newLength = trackPlaylist.clip_length(clipIndex);
1627         mlt_service_unlock(service.get_service());
1628
1629     } else if (serv == "framebuffer") {
1630         mlt_service_lock(service.get_service());
1631         QString url = clip.parent().get("resource");
1632         url = url.section("?", 0, 0);
1633         url.append("?" + QString::number(speed));
1634         Mlt::Producer *slowprod = m_slowmotionProducers.value(url);
1635         if (!slowprod || slowprod->get_producer() == NULL) {
1636             char *tmp = decodedString(url);
1637             slowprod = new Mlt::Producer(*m_mltProfile, "framebuffer", tmp);
1638             delete[] tmp;
1639             QString producerid = "slowmotion:" + id.section(":", 1, 1) + ":" + QString::number(speed);
1640             tmp = decodedString(producerid);
1641             slowprod->set("id", tmp);
1642             delete[] tmp;
1643             m_slowmotionProducers.insert(url, slowprod);
1644         }
1645         trackPlaylist.replace_with_blank(clipIndex);
1646         trackPlaylist.consolidate_blanks(0);
1647
1648         GenTime oldDuration = GenTime(clipLength, m_fps);
1649         GenTime newDuration = oldDuration * oldspeed / speed;
1650
1651         // Check that the blank space is long enough for our new duration
1652         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1653         int blankEnd = trackPlaylist.clip_start(clipIndex) + trackPlaylist.clip_length(clipIndex);
1654
1655         Mlt::Producer *cut;
1656         if (clipIndex + 1 < trackPlaylist.count() && (info.startPos + newDuration).frames(m_fps) > blankEnd) {
1657             GenTime maxLength = GenTime(blankEnd, m_fps) - info.startPos;
1658             cut = slowprod->cut((int)(info.cropStart.frames(m_fps)), (int)(info.cropStart.frames(m_fps) + maxLength.frames(m_fps) - 1));
1659         } else cut = slowprod->cut((int)(info.cropStart.frames(m_fps) / speed), (int)((info.cropStart / speed + newDuration).frames(m_fps) - 1));
1660
1661         trackPlaylist.insert_at(startPos, *cut, 1);
1662         clipIndex = trackPlaylist.get_clip_index_at(startPos);
1663         newLength = trackPlaylist.clip_length(clipIndex);
1664
1665         mlt_service_unlock(service.get_service());
1666     }
1667     if (clipIndex + 1 == trackPlaylist.count()) mltCheckLength();
1668     m_isBlocked = false;
1669     return newLength;
1670 }
1671
1672 bool Render::mltRemoveEffect(int track, GenTime position, QString index, bool doRefresh) {
1673
1674     Mlt::Service service(m_mltProducer->parent().get_service());
1675     bool success = false;
1676     Mlt::Tractor tractor(service);
1677     Mlt::Producer trackProducer(tractor.track(track));
1678     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1679     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1680     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1681     if (!clip) {
1682         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
1683         return success;
1684     }
1685     Mlt::Service clipService(clip->get_service());
1686 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1687     m_isBlocked = true;
1688     int ct = 0;
1689     Mlt::Filter *filter = clipService.filter(ct);
1690     while (filter) {
1691         if ((index == "-1" && filter->get("kdenlive_id") != "")  || filter->get("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
1692             if (clipService.detach(*filter) == 0) success = true;
1693             kDebug() << " / / / DLEETED EFFECT: " << ct;
1694         } else ct++;
1695         filter = clipService.filter(ct);
1696     }
1697     m_isBlocked = false;
1698     if (doRefresh) refresh();
1699     return success;
1700 }
1701
1702
1703 bool Render::mltAddEffect(int track, GenTime position, QHash <QString, QString> args, bool doRefresh) {
1704
1705     Mlt::Service service(m_mltProducer->parent().get_service());
1706
1707     Mlt::Tractor tractor(service);
1708     Mlt::Producer trackProducer(tractor.track(track));
1709     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1710
1711     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1712     if (!clip) {
1713         return false;
1714     }
1715     Mlt::Service clipService(clip->get_service());
1716     m_isBlocked = true;
1717
1718     // temporarily remove all effects after insert point
1719     QList <Mlt::Filter *> filtersList;
1720     const int filer_ix = QString(args.value("kdenlive_ix")).toInt();
1721     int ct = 0;
1722     Mlt::Filter *filter = clipService.filter(ct);
1723     while (filter) {
1724         if (QString(filter->get("kdenlive_ix")).toInt() > filer_ix) {
1725             filtersList.append(filter);
1726             clipService.detach(*filter);
1727         } else ct++;
1728         filter = clipService.filter(ct);
1729     }
1730
1731     // create filter
1732     QString tag = args.value("tag");
1733     kDebug() << " / / INSERTING EFFECT: " << tag;
1734     if (tag.startsWith("ladspa")) tag = "ladspa";
1735     char *filterTag = decodedString(tag);
1736     char *filterId = decodedString(args.value("id"));
1737     QHash<QString, QString>::Iterator it;
1738     QString kfr = args.value("keyframes");
1739
1740     if (!kfr.isEmpty()) {
1741         QStringList keyFrames = kfr.split(";", QString::SkipEmptyParts);
1742         kDebug() << "// ADDING KEYFRAME EFFECT: " << args.value("keyframes");
1743         char *starttag = decodedString(args.value("starttag", "start"));
1744         char *endtag = decodedString(args.value("endtag", "end"));
1745         kDebug() << "// ADDING KEYFRAME TAGS: " << starttag << ", " << endtag;
1746         int duration = clip->get_playtime();
1747         double max = args.value("max").toDouble();
1748         double min = args.value("min").toDouble();
1749         double factor = args.value("factor", "1").toDouble();
1750         args.remove("starttag");
1751         args.remove("endtag");
1752         args.remove("keyframes");
1753         args.remove("min");
1754         args.remove("max");
1755         args.remove("factor");
1756         int offset = 0;
1757         for (int i = 0; i < keyFrames.size() - 1; ++i) {
1758             Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
1759             filter->set("kdenlive_id", filterId);
1760             int x1 = keyFrames.at(i).section(":", 0, 0).toInt() + offset;
1761             double y1 = keyFrames.at(i).section(":", 1, 1).toDouble();
1762             int x2 = keyFrames.at(i + 1).section(":", 0, 0).toInt();
1763             double y2 = keyFrames.at(i + 1).section(":", 1, 1).toDouble();
1764             if (x2 == -1) x2 = duration;
1765             for (it = args.begin(); it != args.end(); ++it) {
1766                 char *name = decodedString(it.key());
1767                 char *value = decodedString(it.value());
1768                 filter->set(name, value);
1769                 delete[] name;
1770                 delete[] value;
1771             }
1772
1773             filter->set("in", x1);
1774             filter->set("out", x2);
1775             //kDebug() << "// ADDING KEYFRAME vals: " << min<<" / "<<max<<", "<<y1<<", factor: "<<factor;
1776             filter->set(starttag, QString::number((min + y1) / factor).toUtf8().data());
1777             filter->set(endtag, QString::number((min + y2) / factor).toUtf8().data());
1778             clipService.attach(*filter);
1779             offset = 1;
1780         }
1781         delete[] starttag;
1782         delete[] endtag;
1783     } else {
1784         Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterTag);
1785         if (filter && filter->is_valid())
1786             filter->set("kdenlive_id", filterId);
1787         else {
1788             kDebug() << "filter is NULL";
1789             m_isBlocked = false;
1790             return false;
1791         }
1792
1793         for (it = args.begin(); it != args.end(); ++it) {
1794             char *name = decodedString(it.key());
1795             char *value = decodedString(it.value());
1796             filter->set(name, value);
1797             delete[] name;
1798             delete[] value;
1799         }
1800         // attach filter to the clip
1801         clipService.attach(*filter);
1802     }
1803     delete[] filterId;
1804     delete[] filterTag;
1805
1806     // re-add following filters
1807     for (int i = 0; i < filtersList.count(); i++) {
1808         clipService.attach(*(filtersList.at(i)));
1809     }
1810
1811     m_isBlocked = false;
1812     if (doRefresh) refresh();
1813     return true;
1814 }
1815
1816 bool Render::mltEditEffect(int track, GenTime position, QHash <QString, QString> args) {
1817     QString index = args.value("kdenlive_ix");
1818     QString tag =  args.value("tag");
1819     QHash<QString, QString>::Iterator it = args.begin();
1820     if (!args.value("keyframes").isEmpty() || /*it.key().startsWith("#") || */tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
1821         // This is a keyframe effect, to edit it, we remove it and re-add it.
1822         mltRemoveEffect(track, position, index);
1823         bool success = mltAddEffect(track, position, args);
1824         return success;
1825     }
1826
1827     // create filter
1828     Mlt::Service service(m_mltProducer->parent().get_service());
1829
1830     Mlt::Tractor tractor(service);
1831     Mlt::Producer trackProducer(tractor.track(track));
1832     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1833     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1834     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1835     if (!clip) {
1836         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1837         return false;
1838     }
1839     Mlt::Service clipService(clip->get_service());
1840     m_isBlocked = true;
1841     int ct = 0;
1842     Mlt::Filter *filter = clipService.filter(ct);
1843     while (filter) {
1844         if (filter->get("kdenlive_ix") == index) {
1845             break;
1846         }
1847         ct++;
1848         filter = clipService.filter(ct);
1849     }
1850
1851     if (!filter) {
1852         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT!!!!!";
1853         // filter was not found, it was probably a disabled filter, so add it to the correct place...
1854         int ct = 0;
1855         filter = clipService.filter(ct);
1856         QList <Mlt::Filter *> filtersList;
1857         while (filter) {
1858             if (QString(filter->get("kdenlive_ix")).toInt() > index.toInt()) {
1859                 filtersList.append(filter);
1860                 clipService.detach(*filter);
1861             } else ct++;
1862             filter = clipService.filter(ct);
1863         }
1864         bool success = mltAddEffect(track, position, args);
1865
1866         for (int i = 0; i < filtersList.count(); i++) {
1867             clipService.attach(*(filtersList.at(i)));
1868         }
1869
1870         m_isBlocked = false;
1871         return success;
1872     }
1873
1874     for (it = args.begin(); it != args.end(); ++it) {
1875         kDebug() << " / / EDITING EFFECT ARGS: " << it.key() << ": " << it.value();
1876         char *name = decodedString(it.key());
1877         char *value = decodedString(it.value());
1878         filter->set(name, value);
1879         delete[] name;
1880         delete[] value;
1881     }
1882     m_isBlocked = false;
1883     refresh();
1884     return true;
1885 }
1886
1887 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos) {
1888
1889     kDebug() << "MOVING EFFECT FROM " << oldPos << ", TO: " << newPos;
1890     Mlt::Service service(m_mltProducer->parent().get_service());
1891
1892     Mlt::Tractor tractor(service);
1893     Mlt::Producer trackProducer(tractor.track(track));
1894     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1895     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1896     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1897     if (!clip) {
1898         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1899         return;
1900     }
1901     Mlt::Service clipService(clip->get_service());
1902     m_isBlocked = true;
1903     int ct = 0;
1904     QList <Mlt::Filter *> filtersList;
1905     Mlt::Filter *filter = clipService.filter(ct);
1906     bool found = false;
1907     if (newPos > oldPos) {
1908         while (filter) {
1909             if (!found && QString(filter->get("kdenlive_ix")).toInt() == oldPos) {
1910                 filter->set("kdenlive_ix", newPos);
1911                 filtersList.append(filter);
1912                 clipService.detach(*filter);
1913                 filter = clipService.filter(ct);
1914                 while (filter && QString(filter->get("kdenlive_ix")).toInt() <= newPos) {
1915                     filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() - 1);
1916                     ct++;
1917                     filter = clipService.filter(ct);
1918                 }
1919                 found = true;
1920             }
1921             if (filter && QString(filter->get("kdenlive_ix")).toInt() > newPos) {
1922                 filtersList.append(filter);
1923                 clipService.detach(*filter);
1924             } else ct++;
1925             filter = clipService.filter(ct);
1926         }
1927     } else {
1928         while (filter) {
1929             if (QString(filter->get("kdenlive_ix")).toInt() == oldPos) {
1930                 filter->set("kdenlive_ix", newPos);
1931                 filtersList.append(filter);
1932                 clipService.detach(*filter);
1933             } else ct++;
1934             filter = clipService.filter(ct);
1935         }
1936
1937         ct = 0;
1938         filter = clipService.filter(ct);
1939         while (filter) {
1940             int pos = QString(filter->get("kdenlive_ix")).toInt();
1941             if (pos >= newPos) {
1942                 if (pos < oldPos) filter->set("kdenlive_ix", pos + 1);
1943                 filtersList.append(filter);
1944                 clipService.detach(*filter);
1945             } else ct++;
1946             filter = clipService.filter(ct);
1947         }
1948     }
1949
1950     for (int i = 0; i < filtersList.count(); i++) {
1951         clipService.attach(*(filtersList.at(i)));
1952     }
1953
1954     m_isBlocked = false;
1955     refresh();
1956 }
1957
1958 bool Render::mltResizeClipEnd(ItemInfo info, GenTime clipDuration) {
1959     m_isBlocked = true;
1960
1961     Mlt::Service service(m_mltProducer->parent().get_service());
1962
1963     Mlt::Tractor tractor(service);
1964     Mlt::Producer trackProducer(tractor.track(info.track));
1965     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1966
1967     /* // Display playlist info
1968     kDebug()<<"////////////  BEFORE RESIZE";
1969     for (int i = 0; i < trackPlaylist.count(); i++) {
1970     int blankStart = trackPlaylist.clip_start(i);
1971     int blankDuration = trackPlaylist.clip_length(i) - 1;
1972     QString blk;
1973     if (trackPlaylist.is_blank(i)) blk = "(blank)";
1974     kDebug()<<"CLIP "<<i<<": ("<<blankStart<<"x"<<blankStart + blankDuration<<")"<<blk;
1975     }*/
1976
1977     if (trackPlaylist.is_blank_at((int) info.startPos.frames(m_fps))) {
1978         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1979         m_isBlocked = false;
1980         return false;
1981     }
1982     int clipIndex = trackPlaylist.get_clip_index_at((int) info.startPos.frames(m_fps));
1983     kDebug() << "// SELECTED CLIP START: " << trackPlaylist.clip_start(clipIndex);
1984     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
1985     int previousStart = clip->get_in();
1986     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;
1987     int newDuration = (int) clipDuration.frames(m_fps) - 1;
1988     trackPlaylist.resize_clip(clipIndex, previousStart, newDuration + previousStart);
1989     //trackPlaylist.consolidate_blanks(0);
1990     // skip to next clip
1991     clipIndex++;
1992     int diff = newDuration - previousDuration;
1993     kDebug() << "////////  RESIZE CLIP: " << clipIndex << "( pos: " << info.startPos.frames(25) << "), DIFF: " << diff << ", CURRENT DUR: " << previousDuration << ", NEW DUR: " << newDuration;
1994     if (diff > 0) {
1995         // clip was made longer, trim next blank if there is one.
1996         if (trackPlaylist.is_blank(clipIndex)) {
1997             int blankStart = trackPlaylist.clip_start(clipIndex);
1998             int blankDuration = trackPlaylist.clip_length(clipIndex) - 1;
1999             if (diff - blankDuration == 1) {
2000                 trackPlaylist.remove(clipIndex);
2001             } else trackPlaylist.resize_clip(clipIndex, blankStart, blankStart + blankDuration - diff);
2002         } else {
2003             kDebug() << "/// RESIZE ERROR, NXT CLIP IS NOT BLK: " << clipIndex;
2004         }
2005     } else trackPlaylist.insert_blank(clipIndex, 0 - diff - 1);
2006
2007     trackPlaylist.consolidate_blanks(0);
2008
2009
2010     if (info.track != 0 && clipIndex == trackPlaylist.count()) mltCheckLength();
2011     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
2012         //mltResizeTransparency(previousStart, previousStart, previousStart + newDuration, track, QString(clip->parent().get("id")).toInt());
2013         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
2014         ItemInfo transpinfo;
2015         transpinfo.startPos = info.startPos;
2016         transpinfo.endPos = info.startPos + clipDuration;
2017         transpinfo.track = info.track;
2018         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
2019     }*/
2020     m_isBlocked = false;
2021     return true;
2022 }
2023
2024 void Render::mltChangeTrackState(int track, bool mute, bool blind) {
2025     Mlt::Service service(m_mltProducer->parent().get_service());
2026     Mlt::Tractor tractor(service);
2027     Mlt::Producer trackProducer(tractor.track(track));
2028     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2029     if (mute) {
2030         if (blind) trackProducer.set("hide", 3);
2031         else trackProducer.set("hide", 2);
2032     } else if (blind) {
2033         trackProducer.set("hide", 1);
2034     } else {
2035         trackProducer.set("hide", 0);
2036     }
2037     tractor.multitrack()->refresh();
2038     tractor.refresh();
2039     refresh();
2040 }
2041
2042 bool Render::mltResizeClipStart(ItemInfo info, GenTime diff) {
2043     //kDebug() << "////////  RSIZING CLIP from: "<<info.startPos.frames(25)<<" to "<<diff.frames(25);
2044     Mlt::Service service(m_mltProducer->parent().get_service());
2045     int moveFrame = (int) diff.frames(m_fps);
2046     Mlt::Tractor tractor(service);
2047     Mlt::Producer trackProducer(tractor.track(info.track));
2048     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2049     if (trackPlaylist.is_blank_at(info.startPos.frames(m_fps))) {
2050         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
2051         return false;
2052     }
2053     mlt_service_lock(service.get_service());
2054     int clipIndex = trackPlaylist.get_clip_index_at(info.startPos.frames(m_fps));
2055     /*int previousStart = trackPlaylist.clip_start(clipIndex);
2056     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;*/
2057     //kDebug() << " ** RESIZING CLIP START:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", moving: " << moveFrame << ", in: " << in.frames(25) << ", out: " << out.frames(25);
2058     Mlt::Producer *clip = trackPlaylist.get_clip(clipIndex);
2059     if (clip == NULL) {
2060         kDebug() << "////////  ERROR RSIZING NULL CLIP!!!!!!!!!!!";
2061         mlt_service_unlock(service.get_service());
2062         return false;
2063     }
2064     //m_mltConsumer->set("refresh", 0);
2065     int previousStart = clip->get_in();
2066     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;
2067     m_isBlocked = true;
2068     kDebug() << "RESIZE, old start: " << previousStart << ", PREV DUR: " << previousDuration << ", DIFF: " << moveFrame;
2069     trackPlaylist.resize_clip(clipIndex, previousStart + moveFrame, previousStart + previousDuration);
2070     if (moveFrame > 0) trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
2071     else {
2072         //int midpos = info.startPos.frames(m_fps) + moveFrame - 1;
2073         int blankIndex = clipIndex - 1;
2074         int blankLength = trackPlaylist.clip_length(blankIndex);
2075         kDebug() << " + resizing blank length " <<  blankLength << ", SIZE DIFF: " << moveFrame;
2076         if (! trackPlaylist.is_blank(blankIndex)) {
2077             kDebug() << "WARNING, CLIP TO RESIZE IS NOT BLANK";
2078         }
2079         if (blankLength + moveFrame == 0) trackPlaylist.remove(blankIndex);
2080         else trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
2081     }
2082     trackPlaylist.consolidate_blanks(0);
2083     /*if (QString(clip->parent().get("transparency")).toInt() == 1) {
2084         //mltResizeTransparency(previousStart, (int) moveEnd.frames(m_fps), (int) (moveEnd + out - in).frames(m_fps), track, QString(clip->parent().get("id")).toInt());
2085         mltDeleteTransparency(info.startPos.frames(m_fps), info.track, QString(clip->parent().get("id")).toInt());
2086         ItemInfo transpinfo;
2087         transpinfo.startPos = info.startPos + diff;
2088         transpinfo.endPos = info.startPos + diff + (info.endPos - info.startPos);
2089         transpinfo.track = info.track;
2090         mltAddClipTransparency(transpinfo, info.track - 1, QString(clip->parent().get("id")).toInt());
2091     }*/
2092     m_isBlocked = false;
2093     //m_mltConsumer->set("refresh", 1);
2094     mlt_service_unlock(service.get_service());
2095     return true;
2096 }
2097
2098 bool Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd, Mlt::Producer *prod) {
2099     return mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps), prod);
2100 }
2101
2102
2103 bool Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd, Mlt::Producer *prod) {
2104     m_isBlocked = true;
2105
2106     m_mltConsumer->set("refresh", 0);
2107     mlt_service_lock(m_mltConsumer->get_service());
2108     Mlt::Service service(m_mltProducer->parent().get_service());
2109     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
2110
2111     Mlt::Tractor tractor(service);
2112     Mlt::Producer trackProducer(tractor.track(startTrack));
2113     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2114     int clipIndex = trackPlaylist.get_clip_index_at(moveStart + 1);
2115     kDebug() << "//////  LOOKING FOR CLIP TO MOVE, INDEX: " << clipIndex;
2116     bool checkLength = false;
2117     if (endTrack == startTrack) {
2118         //mlt_service_lock(service.get_service());
2119         Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
2120
2121         if (!trackPlaylist.is_blank_at(moveEnd)) {
2122             // error, destination is not empty
2123             //int ix = trackPlaylist.get_clip_index_at(moveEnd);
2124             kDebug() << "// ERROR MOVING CLIP TO : " << moveEnd;
2125             mlt_service_unlock(m_mltConsumer->get_service());
2126             m_isBlocked = false;
2127             return false;
2128         } else {
2129             trackPlaylist.consolidate_blanks(0);
2130             int newIndex = trackPlaylist.insert_at(moveEnd, clipProducer, 1);
2131             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
2132                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
2133             }*/
2134             if (newIndex + 1 == trackPlaylist.count()) checkLength = true;
2135         }
2136         //mlt_service_unlock(service.get_service());
2137     } else {
2138         Mlt::Producer destTrackProducer(tractor.track(endTrack));
2139         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
2140         if (!destTrackPlaylist.is_blank_at(moveEnd)) {
2141             // error, destination is not empty
2142             mlt_service_unlock(m_mltConsumer->get_service());
2143             m_isBlocked = false;
2144             return false;
2145         } else {
2146             Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
2147             trackPlaylist.consolidate_blanks(0);
2148             destTrackPlaylist.consolidate_blanks(1);
2149             Mlt::Producer *clip;
2150             // check if we are moving a slowmotion producer
2151             QString serv = clipProducer.parent().get("mlt_service");
2152             if (serv == "framebuffer") {
2153                 clip = &clipProducer;
2154             } else clip = prod->cut(clipProducer.get_in(), clipProducer.get_out());
2155
2156             // move all effects to the correct producer
2157             Mlt::Service clipService(clipProducer.get_service());
2158             Mlt::Service newClipService(clip->get_service());
2159
2160             int ct = 0;
2161             Mlt::Filter *filter = clipService.filter(ct);
2162             while (filter) {
2163                 if (filter->get("kdenlive_ix") != 0) {
2164                     clipService.detach(*filter);
2165                     newClipService.attach(*filter);
2166                 } else ct++;
2167                 filter = clipService.filter(ct);
2168             }
2169
2170             int newIndex = destTrackPlaylist.insert_at(moveEnd, clip, 1);
2171             destTrackPlaylist.consolidate_blanks(0);
2172             /*if (QString(clipProducer.parent().get("transparency")).toInt() == 1) {
2173                 kDebug() << "//////// moving clip transparency";
2174                 mltMoveTransparency(moveStart, moveEnd, startTrack, endTrack, QString(clipProducer.parent().get("id")).toInt());
2175             }*/
2176             if (clipIndex > trackPlaylist.count()) checkLength = true;
2177             else if (newIndex + 1 == destTrackPlaylist.count()) checkLength = true;
2178         }
2179     }
2180
2181     if (checkLength) mltCheckLength();
2182     mlt_service_unlock(m_mltConsumer->get_service());
2183     m_isBlocked = false;
2184     m_mltConsumer->set("refresh", 1);
2185     return true;
2186 }
2187
2188 void Render::mltMoveTransition(QString type, int startTrack, int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut) {
2189     Mlt::Service service(m_mltProducer->parent().get_service());
2190     Mlt::Tractor tractor(service);
2191     Mlt::Field *field = tractor.field();
2192
2193     mlt_service_lock(service.get_service());
2194     m_mltConsumer->set("refresh", 0);
2195     m_isBlocked = true;
2196
2197     mlt_service serv = m_mltProducer->parent().get_service();
2198     mlt_service nextservice = mlt_service_get_producer(serv);
2199     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2200     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2201     QString resource = mlt_properties_get(properties, "mlt_service");
2202     int old_pos = (int)(oldIn.frames(m_fps) + oldOut.frames(m_fps)) / 2;
2203
2204     int new_in = (int)newIn.frames(m_fps);
2205     int new_out = (int)newOut.frames(m_fps) - 1;
2206
2207     while (mlt_type == "transition") {
2208         mlt_transition tr = (mlt_transition) nextservice;
2209         int currentTrack = mlt_transition_get_b_track(tr);
2210         int currentIn = (int) mlt_transition_get_in(tr);
2211         int currentOut = (int) mlt_transition_get_out(tr);
2212
2213         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
2214             mlt_transition_set_in_and_out(tr, new_in, new_out);
2215             if (newTrack - startTrack != 0) {
2216                 kDebug() << "///// TRANSITION CHANGE TRACK. CUrrent (b): " << currentTrack << "x" << mlt_transition_get_a_track(tr) << ", NEw: " << newTrack << "x" << newTransitionTrack;
2217
2218                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
2219                 mlt_properties_set_int(properties, "a_track", newTransitionTrack);
2220                 mlt_properties_set_int(properties, "b_track", newTrack);
2221                 //kDebug() << "set new start & end :" << new_in << new_out<< "TR OFFSET: "<<trackOffset<<", TRACKS: "<<mlt_transition_get_a_track(tr)<<"x"<<mlt_transition_get_b_track(tr);
2222             }
2223             break;
2224         }
2225         nextservice = mlt_service_producer(nextservice);
2226         if (nextservice == NULL) break;
2227         properties = MLT_SERVICE_PROPERTIES(nextservice);
2228         mlt_type = mlt_properties_get(properties, "mlt_type");
2229         resource = mlt_properties_get(properties, "mlt_service");
2230     }
2231     m_isBlocked = false;
2232     mlt_service_unlock(service.get_service());
2233     m_mltConsumer->set("refresh", 1);
2234 }
2235
2236 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
2237     // kDebug() << "update transition"  << tag << " at pos " << in.frames(25);
2238     if (oldTag == tag) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
2239     else {
2240         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
2241         mltAddTransition(tag, a_track, b_track, in, out, xml);
2242     }
2243     //mltSavePlaylist();
2244 }
2245
2246 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
2247     m_isBlocked = true;
2248     Mlt::Service service(m_mltProducer->parent().get_service());
2249     Mlt::Tractor tractor(service);
2250     Mlt::Field *field = tractor.field();
2251
2252     //m_mltConsumer->set("refresh", 0);
2253     mlt_service serv = m_mltProducer->parent().get_service();
2254
2255     mlt_service nextservice = mlt_service_get_producer(serv);
2256     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2257     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2258     QString resource = mlt_properties_get(properties, "mlt_service");
2259     int in_pos = (int) in.frames(m_fps);
2260     int out_pos = (int) out.frames(m_fps) - 1;
2261
2262     while (mlt_type == "transition") {
2263         mlt_transition tr = (mlt_transition) nextservice;
2264         int currentTrack = mlt_transition_get_b_track(tr);
2265         int currentBTrack = mlt_transition_get_a_track(tr);
2266         int currentIn = (int) mlt_transition_get_in(tr);
2267         int currentOut = (int) mlt_transition_get_out(tr);
2268
2269         // kDebug()<<"Looking for transition : " << currentIn <<"x"<<currentOut<< ", OLD oNE: "<<in_pos<<"x"<<out_pos;
2270
2271         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
2272             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
2273             QMap<QString, QString>::Iterator it;
2274             QString key;
2275             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
2276             mlt_properties_set_int(transproperties, "force_track", xml.attribute("force_track").toInt());
2277             if (currentBTrack != a_track) {
2278                 mlt_properties_set_int(properties, "a_track", a_track);
2279             }
2280             for (it = map.begin(); it != map.end(); ++it) {
2281                 key = it.key();
2282                 char *name = decodedString(key);
2283                 char *value = decodedString(it.value());
2284                 mlt_properties_set(transproperties, name, value);
2285                 kDebug() << " ------  UPDATING TRANS PARAM: " << name << ": " << value;
2286                 //filter->set("kdenlive_id", id);
2287                 delete[] name;
2288                 delete[] value;
2289             }
2290             break;
2291         }
2292         nextservice = mlt_service_producer(nextservice);
2293         if (nextservice == NULL) break;
2294         properties = MLT_SERVICE_PROPERTIES(nextservice);
2295         mlt_type = mlt_properties_get(properties, "mlt_type");
2296         resource = mlt_properties_get(properties, "mlt_service");
2297     }
2298     m_isBlocked = false;
2299     m_mltConsumer->set("refresh", 1);
2300 }
2301
2302 void Render::mltDeleteTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
2303     Mlt::Service service(m_mltProducer->parent().get_service());
2304     Mlt::Tractor tractor(service);
2305     Mlt::Field *field = tractor.field();
2306
2307     //if (do_refresh) m_mltConsumer->set("refresh", 0);
2308     mlt_service serv = m_mltProducer->parent().get_service();
2309
2310     mlt_service nextservice = mlt_service_get_producer(serv);
2311     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2312     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2313     QString resource = mlt_properties_get(properties, "mlt_service");
2314
2315     const int old_pos = (int)((in + out).frames(m_fps) / 2);
2316
2317     while (mlt_type == "transition") {
2318         mlt_transition tr = (mlt_transition) nextservice;
2319         int currentTrack = mlt_transition_get_b_track(tr);
2320         int currentIn = (int) mlt_transition_get_in(tr);
2321         int currentOut = (int) mlt_transition_get_out(tr);
2322         //kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
2323
2324         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
2325             mlt_field_disconnect_service(field->get_field(), nextservice);
2326             break;
2327         }
2328         nextservice = mlt_service_producer(nextservice);
2329         if (nextservice == NULL) break;
2330         properties = MLT_SERVICE_PROPERTIES(nextservice);
2331         mlt_type = mlt_properties_get(properties, "mlt_type");
2332         resource = mlt_properties_get(properties, "mlt_service");
2333     }
2334     //if (do_refresh) m_mltConsumer->set("refresh", 1);
2335 }
2336
2337 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml) {
2338     QDomNodeList attribs = xml.elementsByTagName("parameter");
2339     QMap<QString, QString> map;
2340     for (int i = 0;i < attribs.count();i++) {
2341         QDomElement e = attribs.item(i).toElement();
2342         QString name = e.attribute("name");
2343         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
2344         map[name] = e.attribute("default");
2345         if (!e.attribute("value").isEmpty()) {
2346             map[name] = e.attribute("value");
2347         }
2348         if (!e.attribute("factor").isEmpty() && e.attribute("factor").toDouble() > 0) {
2349             map[name] = QString::number(map[name].toDouble() / e.attribute("factor").toDouble());
2350             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
2351         }
2352
2353         if (e.attribute("namedesc").contains(";")) {
2354             QString format = e.attribute("format");
2355             QStringList separators = format.split("%d", QString::SkipEmptyParts);
2356             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
2357             QString neu;
2358             QTextStream txtNeu(&neu);
2359             if (values.size() > 0)
2360                 txtNeu << (int)values[0].toDouble();
2361             int i = 0;
2362             for (i = 0;i < separators.size() && i + 1 < values.size();i++) {
2363                 txtNeu << separators[i];
2364                 txtNeu << (int)(values[i+1].toDouble());
2365             }
2366             if (i < separators.size())
2367                 txtNeu << separators[i];
2368             map[e.attribute("name")] = neu;
2369         }
2370
2371     }
2372     return map;
2373 }
2374
2375 void Render::mltAddClipTransparency(ItemInfo info, int transitiontrack, int id) {
2376     kDebug() << "/////////  ADDING CLIP TRANSPARENCY AT: " << info.startPos.frames(25);
2377     Mlt::Service service(m_mltProducer->parent().get_service());
2378     Mlt::Tractor tractor(service);
2379     Mlt::Field *field = tractor.field();
2380
2381     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
2382     transition->set_in_and_out((int) info.startPos.frames(m_fps), (int) info.endPos.frames(m_fps) - 1);
2383     transition->set("transparency", id);
2384     transition->set("fill", 1);
2385     transition->set("internal_added", 237);
2386     field->plant_transition(*transition, transitiontrack, info.track);
2387     refresh();
2388 }
2389
2390 void Render::mltDeleteTransparency(int pos, int track, int id) {
2391     Mlt::Service service(m_mltProducer->parent().get_service());
2392     Mlt::Tractor tractor(service);
2393     Mlt::Field *field = tractor.field();
2394
2395     //if (do_refresh) m_mltConsumer->set("refresh", 0);
2396     mlt_service serv = m_mltProducer->parent().get_service();
2397
2398     mlt_service nextservice = mlt_service_get_producer(serv);
2399     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2400     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2401     QString resource = mlt_properties_get(properties, "mlt_service");
2402
2403     while (mlt_type == "transition") {
2404         mlt_transition tr = (mlt_transition) nextservice;
2405         int currentTrack = mlt_transition_get_b_track(tr);
2406         int currentIn = (int) mlt_transition_get_in(tr);
2407         int currentOut = (int) mlt_transition_get_out(tr);
2408         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
2409         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
2410
2411         if (resource == "composite" && track == currentTrack && currentIn == pos && transitionId == id) {
2412             //kDebug() << " / / / / /DELETE TRANS DOOOMNE";
2413             mlt_field_disconnect_service(field->get_field(), nextservice);
2414             break;
2415         }
2416         nextservice = mlt_service_producer(nextservice);
2417         if (nextservice == NULL) break;
2418         properties = MLT_SERVICE_PROPERTIES(nextservice);
2419         mlt_type = mlt_properties_get(properties, "mlt_type");
2420         resource = mlt_properties_get(properties, "mlt_service");
2421     }
2422     //if (do_refresh) m_mltConsumer->set("refresh", 1);
2423 }
2424
2425 void Render::mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id) {
2426     Mlt::Service service(m_mltProducer->parent().get_service());
2427     Mlt::Tractor tractor(service);
2428     Mlt::Field *field = tractor.field();
2429
2430     mlt_service_lock(service.get_service());
2431     m_mltConsumer->set("refresh", 0);
2432     m_isBlocked = true;
2433
2434     mlt_service serv = m_mltProducer->parent().get_service();
2435     mlt_service nextservice = mlt_service_get_producer(serv);
2436     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2437     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2438     QString resource = mlt_properties_get(properties, "mlt_service");
2439     kDebug() << "// resize transpar from: " << oldStart << ", TO: " << newStart << "x" << newEnd << ", " << track << ", " << id;
2440     while (mlt_type == "transition") {
2441         mlt_transition tr = (mlt_transition) nextservice;
2442         int currentTrack = mlt_transition_get_b_track(tr);
2443         int currentIn = (int) mlt_transition_get_in(tr);
2444         //mlt_properties props = MLT_TRANSITION_PROPERTIES(tr);
2445         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
2446         kDebug() << "// resize transpar current in: " << currentIn << ", Track: " << currentTrack << ", id: " << id << "x" << transitionId ;
2447         if (resource == "composite" && track == currentTrack && currentIn == oldStart && transitionId == id) {
2448             kDebug() << " / / / / /RESIZE TRANS TO: " << newStart << "x" << newEnd;
2449             mlt_transition_set_in_and_out(tr, newStart, newEnd);
2450             break;
2451         }
2452         nextservice = mlt_service_producer(nextservice);
2453         if (nextservice == NULL) break;
2454         properties = MLT_SERVICE_PROPERTIES(nextservice);
2455         mlt_type = mlt_properties_get(properties, "mlt_type");
2456         resource = mlt_properties_get(properties, "mlt_service");
2457     }
2458     m_isBlocked = false;
2459     mlt_service_unlock(service.get_service());
2460     m_mltConsumer->set("refresh", 1);
2461
2462 }
2463
2464 void Render::mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id) {
2465     Mlt::Service service(m_mltProducer->parent().get_service());
2466     Mlt::Tractor tractor(service);
2467     Mlt::Field *field = tractor.field();
2468
2469     mlt_service_lock(service.get_service());
2470     m_mltConsumer->set("refresh", 0);
2471     m_isBlocked = true;
2472
2473     mlt_service serv = m_mltProducer->parent().get_service();
2474     mlt_service nextservice = mlt_service_get_producer(serv);
2475     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
2476     QString mlt_type = mlt_properties_get(properties, "mlt_type");
2477     QString resource = mlt_properties_get(properties, "mlt_service");
2478
2479     while (mlt_type == "transition") {
2480         mlt_transition tr = (mlt_transition) nextservice;
2481         int currentTrack = mlt_transition_get_b_track(tr);
2482         int currentaTrack = mlt_transition_get_a_track(tr);
2483         int currentIn = (int) mlt_transition_get_in(tr);
2484         int currentOut = (int) mlt_transition_get_out(tr);
2485         //mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
2486         int transitionId = QString(mlt_properties_get(properties, "transparency")).toInt();
2487         //kDebug()<<" + TRANSITION "<<id<<" == "<<transitionId<<", START TMIE: "<<currentIn<<", LOOK FR: "<<startTime<<", TRACK: "<<currentTrack<<"x"<<startTrack;
2488         if (resource == "composite" && transitionId == id && startTime == currentIn && startTrack == currentTrack) {
2489             kDebug() << "//////MOVING";
2490             mlt_transition_set_in_and_out(tr, endTime, endTime + currentOut - currentIn);
2491             if (endTrack != startTrack) {
2492                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
2493                 mlt_properties_set_int(properties, "a_track", currentaTrack + endTrack - currentTrack);
2494                 mlt_properties_set_int(properties, "b_track", endTrack);
2495             }
2496             break;
2497         }
2498         nextservice = mlt_service_producer(nextservice);
2499         if (nextservice == NULL) break;
2500         properties = MLT_SERVICE_PROPERTIES(nextservice);
2501         mlt_type = mlt_properties_get(properties, "mlt_type");
2502         resource = mlt_properties_get(properties, "mlt_service");
2503     }
2504     m_isBlocked = false;
2505     mlt_service_unlock(service.get_service());
2506     m_mltConsumer->set("refresh", 1);
2507 }
2508
2509
2510 void Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
2511
2512     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
2513     Mlt::Service service(m_mltProducer->parent().get_service());
2514
2515     Mlt::Tractor tractor(service);
2516     Mlt::Field *field = tractor.field();
2517
2518     char *transId = decodedString(tag);
2519     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, transId);
2520     if (out != GenTime())
2521         transition->set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps) - 1);
2522     QMap<QString, QString>::Iterator it;
2523     QString key;
2524     if (xml.attribute("automatic") == "1") transition->set("automatic", 1);
2525     //kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
2526
2527     for (it = args.begin(); it != args.end(); ++it) {
2528         key = it.key();
2529         char *name = decodedString(key);
2530         char *value = decodedString(it.value());
2531         transition->set(name, value);
2532         kDebug() << " ------  ADDING TRANS PARAM: " << name << ": " << value;
2533         //filter->set("kdenlive_id", id);
2534         delete[] name;
2535         delete[] value;
2536     }
2537     // attach filter to the clip
2538     field->plant_transition(*transition, a_track, b_track);
2539     delete[] transId;
2540     refresh();
2541 }
2542
2543 void Render::mltSavePlaylist() {
2544     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
2545     Mlt::Consumer fileConsumer(*m_mltProfile, "westley");
2546     fileConsumer.set("resource", "/tmp/playlist.westley");
2547
2548     Mlt::Service service(m_mltProducer->get_service());
2549
2550     fileConsumer.connect(service);
2551     fileConsumer.start();
2552 }
2553
2554 QList <Mlt::Producer *> Render::producersList() {
2555     QList <Mlt::Producer *> prods;
2556     QStringList ids;
2557     Mlt::Service service(m_mltProducer->parent().get_service());
2558     Mlt::Tractor tractor(service);
2559     Mlt::Field *field = tractor.field();
2560
2561     int trackNb = tractor.count();
2562     for (int t = 1; t < trackNb; t++) {
2563         Mlt::Producer trackProducer(tractor.track(t));
2564         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
2565         int clipNb = trackPlaylist.count();
2566         kDebug() << "// PARSING SCENE TRACK: " << t << ", CLIPS: " << clipNb;
2567         for (int i = 0; i < clipNb; i++) {
2568             Mlt::Producer *prod = trackPlaylist.get_clip(i);
2569             Mlt::Producer *nprod = new Mlt::Producer(prod->get_parent());
2570             //kDebug()<<"PROD: "<<nprod->get("producer")<<", ID: "<<nprod->get("id")<<nprod->get("resource");
2571             if (nprod && !nprod->is_blank() && !ids.contains(nprod->get("id"))) {
2572                 ids.append(nprod->get("id"));
2573                 prods.append(nprod);
2574             }
2575         }
2576     }
2577     return prods;
2578 }
2579
2580 #include "renderer.moc"
2581