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