]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Fix move effects up and down in stack
[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@ader.ch
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 <QTimer>
32 #include <QDir>
33 #include <QApplication>
34 #include <QPainter>
35
36 #include <KDebug>
37 #include <KStandardDirs>
38 #include <KMessageBox>
39 #include <KLocale>
40 #include <KTemporaryFile>
41
42 #include "renderer.h"
43 #include "kdenlivesettings.h"
44 #include "kthumb.h"
45 //#include <ffmpeg/avformat.h>
46 #include <mlt++/Mlt.h>
47
48 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr) {
49     // detect if the producer has finished playing. Is there a better way to do it ?
50     //if (self->isBlocked) return;
51     if (mlt_properties_get_double(MLT_FRAME_PROPERTIES(frame_ptr), "_speed") == 0.0) {
52         self->emitConsumerStopped();
53     } else {
54         self->emitFrameNumber(mlt_frame_get_position(frame_ptr));
55     }
56 }
57
58 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(-1), m_framePosition(0), m_generateScenelist(false), m_isBlocked(true) {
59     kDebug() << "//////////  USING PROFILE: " << (char *)KdenliveSettings::current_profile().toUtf8().data();
60     m_mltProfile = new Mlt::Profile((char*) KdenliveSettings::current_profile().data());
61     refreshTimer = new QTimer(this);
62     connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
63
64     m_connectTimer = new QTimer(this);
65     connect(m_connectTimer, SIGNAL(timeout()), this, SLOT(connectPlaylist()));
66
67     if (rendererName == "project") m_monitorId = 10000;
68     else m_monitorId = 10001;
69     osdTimer = new QTimer(this);
70     connect(osdTimer, SIGNAL(timeout()), this, SLOT(slotOsdTimeout()));
71
72     m_osdProfile =   KStandardDirs::locate("data", "kdenlive/profiles/metadata.properties");
73     //if (rendererName == "clip")
74     {
75         //Mlt::Consumer *consumer = new Mlt::Consumer( profile , "sdl_preview");
76         m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview"); //consumer;
77         m_mltConsumer->set("resize", 1);
78         m_mltConsumer->set("window_id", winid);
79         m_mltConsumer->set("terminate_on_pause", 1);
80         m_mltConsumer->set("rescale", "nearest");
81         m_mltConsumer->set("progressive", 1);
82         m_mltConsumer->set("audio_buffer", 1024);
83         m_mltConsumer->set("frequency", 48000);
84         m_externalwinid = extid;
85         m_winid = winid;
86         m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
87         Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "westley-xml", "<westley><playlist><producer mlt_service=\"colour\" colour=\"blue\" in=\"0\" out=\"25\" /></playlist></westley>");
88         m_mltProducer = producer;
89         m_mltConsumer->connect(*m_mltProducer);
90         m_mltProducer->set_speed(0.0);
91
92         //m_mltConsumer->start();
93         //refresh();
94         //initSceneList();
95     }
96     /*m_osdInfo = new Mlt::Filter("data_show");
97     char *tmp = decodedString(m_osdProfile);
98     m_osdInfo->set("resource", tmp);
99     delete[] tmp;*/
100     //      Does it do anything usefull? I mean, RenderThread doesn't do anything useful at the moment
101     //      (except being cpu hungry :)
102
103     /*      if(!s_renderThread) {
104     s_renderThread = new RenderThread;
105     s_renderThread->start();
106     } */
107 }
108
109 Render::~Render() {
110     closeMlt();
111 }
112
113
114 void Render::closeMlt() {
115     delete m_connectTimer;
116     delete osdTimer;
117     delete refreshTimer;
118     if (m_mltConsumer)
119         delete m_mltConsumer;
120     if (m_mltProducer)
121         delete m_mltProducer;
122     //delete m_osdInfo;
123 }
124
125
126
127 int Render::resetProfile(QString profile) {
128     if (!m_mltConsumer) return 0;
129     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
130     m_mltConsumer->set("refresh", 0);
131     m_mltConsumer->purge();
132     delete m_mltConsumer;
133     m_mltConsumer = NULL;
134     QString scene = sceneList();
135     if (m_mltProducer) delete m_mltProducer;
136     m_mltProducer = NULL;
137     if (m_mltProfile) delete m_mltProfile;
138     m_mltProfile = NULL;
139
140     m_mltProfile = new Mlt::Profile((char*) profile.toUtf8().data());
141     m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview"); //consumer;
142     m_mltConsumer->set("resize", 1);
143     m_mltConsumer->set("window_id", m_winid);
144     m_mltConsumer->set("terminate_on_pause", 1);
145     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
146     m_mltConsumer->set("rescale", "nearest");
147     m_mltConsumer->set("progressive", 1);
148     m_mltConsumer->set("audio_buffer", 1024);
149     m_mltConsumer->set("frequency", 48000);
150
151     Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "westley-xml", (char *) scene.toUtf8().data());
152     m_mltProducer = producer;
153     m_mltConsumer->connect(*m_mltProducer);
154     m_mltProducer->set_speed(0.0);
155
156     //delete m_mltProfile;
157     // mlt_properties properties = MLT_CONSUMER_PROPERTIES(m_mltConsumer->get_consumer());
158     //mlt_profile prof = m_mltProfile->get_profile();
159     //mlt_properties_set_data(properties, "_profile", prof, 0, (mlt_destructor)mlt_profile_close, NULL);
160     //mlt_properties_set(properties, "profile", "hdv_1080_50i");
161     //m_mltConsumer->set("profile", (char *) profile.toUtf8().data());
162     //m_mltProfile = new Mlt::Profile((char*) profile.toUtf8().data());
163     kDebug() << " ++++++++++ RESET CONSUMER WITH PROFILE: " << profile << ", WIDTH: " << m_mltProfile->width();
164
165     //apply_profile_properties( m_mltProfile, m_mltConsumer->get_consumer(), properties );
166     //refresh();
167     return 1;
168 }
169
170 /** Wraps the VEML command of the same name; Seeks the renderer clip to the given time. */
171 void Render::seek(GenTime time) {
172     sendSeekCommand(time);
173     //emit positionChanged(time);
174 }
175
176 //static
177 char *Render::decodedString(QString str) {
178     /*QCString fn = QFile::encodeName(str);
179     char *t = new char[fn.length() + 1];
180     strcpy(t, (const char *)fn);*/
181
182     return (char *) qstrdup(str.toUtf8().data());   //toLatin1
183 }
184
185 //static
186 /*QPixmap Render::frameThumbnail(Mlt::Frame *frame, int width, int height, bool border) {
187     QPixmap pix(width, height);
188
189     mlt_image_format format = mlt_image_rgb24a;
190     uint8_t *thumb = frame->get_image(format, width, height);
191     QImage image(thumb, width, height, QImage::Format_ARGB32);
192
193     if (!image.isNull()) {
194         pix = pix.fromImage(image);
195         if (border) {
196             QPainter painter(&pix);
197             painter.drawRect(0, 0, width - 1, height - 1);
198         }
199     } else pix.fill(Qt::black);
200     return pix;
201 }
202 */
203 const int Render::renderWidth() const {
204     return (int)(m_mltProfile->height() * m_mltProfile->dar());
205 }
206
207 const int Render::renderHeight() const {
208     return m_mltProfile->height();
209 }
210
211 QPixmap Render::extractFrame(int frame_position, int width, int height) {
212     if (width == -1) {
213         width = renderWidth();
214         height = renderHeight();
215     }
216     QPixmap pix(width, height);
217     if (!m_mltProducer) {
218         pix.fill(Qt::black);
219         return pix;
220     }
221     //Mlt::Producer *mlt_producer = m_mltProducer->cut(frame_position, frame_position + 1);
222     return KThumb::getFrame(m_mltProducer, frame_position, width, height);
223     /*Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
224     m_convert.set("forced", mlt_image_rgb24a);
225     mlt_producer->attach(m_convert);
226     Mlt::Frame *frame = mlt_producer->get_frame();
227
228     if (frame) {
229         pix = frameThumbnail(frame, width, height);
230         delete frame;
231     } else pix.fill(Qt::black);
232     delete mlt_producer;
233     return pix;*/
234 }
235
236 QPixmap Render::getImageThumbnail(KUrl url, int width, int height) {
237     QImage im;
238     QPixmap pixmap;
239     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
240         QString fileType = url.fileName().right(3);
241         QStringList more;
242         QStringList::Iterator it;
243
244         QDir dir(url.directory());
245         more = dir.entryList(QDir::Files);
246
247         for (it = more.begin() ; it != more.end() ; ++it) {
248             if ((*it).endsWith("." + fileType, Qt::CaseInsensitive)) {
249                 im.load(url.directory() + "/" + *it);
250                 break;
251             }
252         }
253     } else im.load(url.path());
254     //pixmap = im.scaled(width, height);
255     return pixmap;
256 }
257 /*
258 //static
259 QPixmap Render::getVideoThumbnail(char *profile, QString file, int frame_position, int width, int height) {
260     QPixmap pix(width, height);
261     char *tmp = decodedString(file);
262     Mlt::Profile *prof = new Mlt::Profile(profile);
263     Mlt::Producer m_producer(*prof, tmp);
264     delete[] tmp;
265     if (m_producer.is_blank()) {
266         pix.fill(Qt::black);
267         return pix;
268     }
269
270     Mlt::Filter m_convert(*prof, "avcolour_space");
271     m_convert.set("forced", mlt_image_rgb24a);
272     m_producer.attach(m_convert);
273     m_producer.seek(frame_position);
274     Mlt::Frame * frame = m_producer.get_frame();
275     if (frame) {
276         pix = frameThumbnail(frame, width, height, true);
277         delete frame;
278     }
279     if (prof) delete prof;
280     return pix;
281 }
282 */
283 /*
284 void Render::getImage(KUrl url, int frame_position, QPoint size)
285 {
286     char *tmp = decodedString(url.path());
287     Mlt::Producer m_producer(tmp);
288     delete[] tmp;
289     if (m_producer.is_blank()) {
290  return;
291     }
292     Mlt::Filter m_convert("avcolour_space");
293     m_convert.set("forced", mlt_image_rgb24a);
294     m_producer.attach(m_convert);
295     m_producer.seek(frame_position);
296
297     Mlt::Frame * frame = m_producer.get_frame();
298
299     if (frame) {
300  QPixmap pix = frameThumbnail(frame, size.x(), size.y(), true);
301  delete frame;
302  emit replyGetImage(url, frame_position, pix, size.x(), size.y());
303     }
304 }*/
305
306 /* Create thumbnail for color */
307 /*void Render::getImage(int id, QString color, QPoint size)
308 {
309     QPixmap pixmap(size.x() - 2, size.y() - 2);
310     color = color.replace(0, 2, "#");
311     color = color.left(7);
312     pixmap.fill(QColor(color));
313     QPixmap result(size.x(), size.y());
314     result.fill(Qt::black);
315     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
316     emit replyGetImage(id, result, size.x(), size.y());
317
318 }*/
319
320 /* Create thumbnail for image */
321 /*void Render::getImage(KUrl url, QPoint size)
322 {
323     QImage im;
324     QPixmap pixmap;
325     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
326      QString fileType = url.fileName().right(3);
327          QStringList more;
328          QStringList::Iterator it;
329
330             QDir dir( url.directory() );
331             more = dir.entryList( QDir::Files );
332             for ( it = more.begin() ; it != more.end() ; ++it ) {
333                 if ((*it).endsWith("."+fileType, Qt::CaseInsensitive)) {
334    if (!im.load(url.directory() + "/" + *it))
335        kDebug()<<"++ ERROR LOADIN IMAGE: "<<url.directory() + "/" + *it;
336    break;
337   }
338      }
339     }
340     else im.load(url.path());
341
342     //pixmap = im.smoothScale(size.x() - 2, size.y() - 2);
343     QPixmap result(size.x(), size.y());
344     result.fill(Qt::black);
345     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
346     emit replyGetImage(url, 1, result, size.x(), size.y());
347 }*/
348
349
350 double Render::consumerRatio() const {
351     if (!m_mltConsumer) return 1.0;
352     return (m_mltConsumer->get_double("aspect_ratio_num") / m_mltConsumer->get_double("aspect_ratio_den"));
353 }
354
355
356 int Render::getLength() {
357
358     if (m_mltProducer) {
359         // kDebug()<<"//////  LENGTH: "<<mlt_producer_get_playtime(m_mltProducer->get_producer());
360         return mlt_producer_get_playtime(m_mltProducer->get_producer());
361     }
362     return 0;
363 }
364
365 bool Render::isValid(KUrl url) {
366     char *tmp = decodedString(url.path());
367     Mlt::Producer producer(*m_mltProfile, tmp);
368     delete[] tmp;
369     if (producer.is_blank())
370         return false;
371
372     return true;
373 }
374
375 void Render::getFileProperties(const QDomElement &xml, int clipId) {
376     int height = 40;
377     int width = (int)(height  * m_mltProfile->dar());
378     QDomDocument doc;
379     QDomElement westley = doc.createElement("westley");
380     doc.appendChild(westley);
381     westley.appendChild(doc.importNode(xml, true));
382     //kDebug() << "////////////\n" << doc.toString() << "////////////////\n";
383     char *tmp = decodedString(doc.toString());
384
385     Mlt::Producer producer(*m_mltProfile, "westley-xml", tmp);
386     delete[] tmp;
387
388     if (producer.is_blank()) {
389         return;
390     }
391     int frameNumber = xml.attribute("frame_thumbnail", 0).toInt();
392     if (frameNumber != 0) producer.seek(frameNumber);
393     mlt_properties properties = MLT_PRODUCER_PROPERTIES(producer.get_producer());
394
395     QMap < QString, QString > filePropertyMap;
396     QMap < QString, QString > metadataPropertyMap;
397
398     KUrl url = xml.attribute("resource", QString::null);
399     filePropertyMap["filename"] = url.path();
400     filePropertyMap["duration"] = QString::number(producer.get_playtime());
401     kDebug() << "///////  PRODUCER: " << url.path() << " IS: " << producer.get_playtime();
402     Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
403     m_convert.set("forced", mlt_image_rgb24a);
404     producer.attach(m_convert);
405     Mlt::Frame * frame = producer.get_frame();
406
407     //filePropertyMap["fps"] = QString::number(mlt_producer_get_fps(producer.get_producer()));
408     filePropertyMap["fps"] = producer.get("source_fps");
409
410     if (frame && frame->is_valid()) {
411         filePropertyMap["frame_size"] = QString::number(frame->get_int("width")) + "x" + QString::number(frame->get_int("height"));
412         filePropertyMap["frequency"] = QString::number(frame->get_int("frequency"));
413         filePropertyMap["channels"] = QString::number(frame->get_int("channels"));
414         filePropertyMap["aspect_ratio"] = frame->get("aspect_ratio");
415
416         if (frame->get_int("test_image") == 0) {
417             if (url.path().endsWith(".westley") || url.path().endsWith(".kdenlive")) {
418                 filePropertyMap["type"] = "playlist";
419                 metadataPropertyMap["comment"] = QString::fromUtf8(mlt_properties_get(MLT_SERVICE_PROPERTIES(producer.get_service()), "title"));
420             } else if (frame->get_int("test_audio") == 0)
421                 filePropertyMap["type"] = "av";
422             else
423                 filePropertyMap["type"] = "video";
424
425             // Generate thumbnail for this frame
426             QPixmap pixmap = KThumb::getFrame(&producer, 0, width, height);
427
428             emit replyGetImage(clipId, 0, pixmap, width, height);
429
430         } else if (frame->get_int("test_audio") == 0) {
431             QPixmap pixmap(KStandardDirs::locate("appdata", "graphics/music.png"));
432             emit replyGetImage(clipId, 0, pixmap, width, height);
433             filePropertyMap["type"] = "audio";
434         }
435     }
436
437     // Retrieve audio / video codec name
438
439     // Fetch the video_context
440 #if 1
441     AVFormatContext *context = (AVFormatContext *) mlt_properties_get_data(properties, "video_context", NULL);
442     if (context != NULL) {
443         // Get the video_index
444         int index = mlt_properties_get_int(properties, "video_index");
445         if (context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->name)
446             filePropertyMap["videocodec"] = context->streams[ index ]->codec->codec->name;
447     }
448     context = (AVFormatContext *) mlt_properties_get_data(properties, "audio_context", NULL);
449     if (context != NULL) {
450         // Get the video_index
451         int index = mlt_properties_get_int(properties, "audio_index");
452         if (context->streams && context->streams [index] && context->streams[ index ]->codec && context->streams[ index ]->codec->codec->name)
453             filePropertyMap["audiocodec"] = context->streams[ index ]->codec->codec->name;
454     }
455 #endif
456     // metadata
457
458     mlt_properties metadata = mlt_properties_new();
459     mlt_properties_pass(metadata, properties, "meta.attr.");
460     int count = mlt_properties_count(metadata);
461     for (int i = 0; i < count; i ++) {
462         QString name = mlt_properties_get_name(metadata, i);
463         QString value = QString::fromUtf8(mlt_properties_get_value(metadata, i));
464         if (name.endsWith("markup") && !value.isEmpty())
465             metadataPropertyMap[ name.section(".", 0, -2)] = value;
466     }
467
468     emit replyGetFileProperties(clipId, filePropertyMap, metadataPropertyMap);
469     kDebug() << "REquested fuile info for: " << url.path();
470     if (frame) delete frame;
471 }
472
473 /** Create the producer from the Westley QDomDocument */
474 #if 0
475 void Render::initSceneList() {
476     kDebug() << "--------  INIT SCENE LIST ------_";
477     QDomDocument doc;
478     QDomElement westley = doc.createElement("westley");
479     doc.appendChild(westley);
480     QDomElement prod = doc.createElement("producer");
481     prod.setAttribute("resource", "colour");
482     prod.setAttribute("colour", "red");
483     prod.setAttribute("id", "black");
484     prod.setAttribute("in", "0");
485     prod.setAttribute("out", "0");
486
487     QDomElement tractor = doc.createElement("tractor");
488     QDomElement multitrack = doc.createElement("multitrack");
489
490     QDomElement playlist1 = doc.createElement("playlist");
491     playlist1.appendChild(prod);
492     multitrack.appendChild(playlist1);
493     QDomElement playlist2 = doc.createElement("playlist");
494     multitrack.appendChild(playlist2);
495     QDomElement playlist3 = doc.createElement("playlist");
496     multitrack.appendChild(playlist3);
497     QDomElement playlist4 = doc.createElement("playlist");
498     multitrack.appendChild(playlist4);
499     QDomElement playlist5 = doc.createElement("playlist");
500     multitrack.appendChild(playlist5);
501     tractor.appendChild(multitrack);
502     westley.appendChild(tractor);
503     // kDebug()<<doc.toString();
504     /*
505        QString tmp = QString("<westley><producer resource=\"colour\" colour=\"red\" id=\"red\" /><tractor><multitrack><playlist></playlist><playlist></playlist><playlist /><playlist /><playlist></playlist></multitrack></tractor></westley>");*/
506     setSceneList(doc, 0);
507 }
508 #endif
509 /** Create the producer from the Westley QDomDocument */
510 void Render::setSceneList(QDomDocument list, int position) {
511     setSceneList(list.toString(), position);
512 }
513
514 /** Create the producer from the Westley QDomDocument */
515 void Render::setSceneList(QString playlist, int position) {
516     if (m_winid == -1) return;
517     m_generateScenelist = true;
518
519     //kWarning() << "//////  RENDER, SET SCENE LIST: " << playlist;
520
521
522     /*
523         if (!clip.is_valid()) {
524      kWarning()<<" ++++ WARNING, UNABLE TO CREATE MLT PRODUCER";
525      m_generateScenelist = false;
526      return;
527         }*/
528
529     if (m_mltConsumer) {
530         m_mltConsumer->stop();
531         m_mltConsumer->set("refresh", 0);
532     } else return;
533     if (m_mltProducer) {
534         m_mltProducer->set_speed(0.0);
535         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
536
537         delete m_mltProducer;
538         m_mltProducer = NULL;
539         emit stopped();
540     }
541
542     char *tmp = decodedString(playlist);
543     m_mltProducer = new Mlt::Producer(*m_mltProfile, "westley-xml", tmp);
544     delete[] tmp;
545     if (!m_mltProducer || !m_mltProducer->is_valid()) kDebug() << " WARNING - - - - -INVALID PLAYLIST: " << tmp;
546     //m_mltProducer->optimise();
547     if (position != 0) m_mltProducer->seek(position);
548
549     /*if (KdenliveSettings::osdtimecode()) {
550     // Attach filter for on screen display of timecode
551     delete m_osdInfo;
552     QString attr = "attr_check";
553     mlt_filter filter = mlt_factory_filter( "data_feed", (char*) attr.ascii() );
554     mlt_properties_set_int( MLT_FILTER_PROPERTIES( filter ), "_fezzik", 1 );
555     mlt_producer_attach( m_mltProducer->get_producer(), filter );
556     mlt_filter_close( filter );
557
558       m_osdInfo = new Mlt::Filter("data_show");
559     tmp = decodedString(m_osdProfile);
560       m_osdInfo->set("resource", tmp);
561     delete[] tmp;
562     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
563     mlt_properties_set_int( properties, "meta.attr.timecode", 1);
564     mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
565     m_osdInfo->set("dynamic", "1");
566
567       if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
568     } else {
569     m_osdInfo->set("dynamic", "0");
570     }*/
571
572     m_fps = m_mltProducer->get_fps();
573     emit durationChanged(m_mltProducer->get_playtime());
574     //m_connectTimer->start( 1000 );
575     connectPlaylist();
576     m_generateScenelist = false;
577
578 }
579
580 /** Create the producer from the Westley QDomDocument */
581 QString Render::sceneList() {
582     KTemporaryFile temp;
583     QString result;
584
585     if (temp.open()) {
586         saveSceneList(temp.fileName());
587         QFile file(temp.fileName());
588         if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
589             kWarning() << "++++++++++++++++   CANNOT READ TMP SCENELIST FILE";
590             return QString();
591         }
592         QTextStream in(&file);
593         while (!in.atEnd()) {
594             result.append(in.readLine());
595         }
596     }
597     return result;
598 }
599
600 void Render::saveSceneList(QString path, QDomElement kdenliveData) {
601
602     char *tmppath = decodedString("westley:" + path);
603     Mlt::Consumer westleyConsumer(*m_mltProfile , tmppath);
604     delete[] tmppath;
605     westleyConsumer.set("terminate_on_pause", 1);
606     Mlt::Producer prod(m_mltProducer->get_producer());
607     westleyConsumer.connect(prod);
608     //prod.set("title", "kdenlive document");
609     //westleyConsumer.listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
610     westleyConsumer.start();
611     while (!westleyConsumer.is_stopped()) {}
612     if (!kdenliveData.isNull()) {
613         // add Kdenlive specific tags
614         QFile file(path);
615         QDomDocument doc;
616         doc.setContent(&file, false);
617         QDomNode wes = doc.elementsByTagName("westley").at(0);
618         wes.appendChild(doc.importNode(kdenliveData, true));
619         file.close();
620         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
621             kWarning() << "//////  ERROR writing to file: " << path;
622             return;
623         }
624         QTextStream out(&file);
625         out << doc.toString();
626         file.close();
627     }
628 }
629
630
631 const double Render::fps() const {
632     return m_fps;
633 }
634
635 void Render::connectPlaylist() {
636     if (!m_mltConsumer) return;
637     m_connectTimer->stop();
638     m_mltConsumer->set("refresh", "0");
639     m_mltConsumer->connect(*m_mltProducer);
640     m_mltProducer->set_speed(0.0);
641     m_mltConsumer->start();
642     refresh();
643     /*
644      if (m_mltConsumer->start() == -1) {
645           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."));
646           m_mltConsumer = NULL;
647      }
648      else {
649              refresh();
650      }*/
651 }
652
653 void Render::refreshDisplay() {
654
655     if (!m_mltProducer) return;
656     m_mltConsumer->set("refresh", 0);
657
658     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
659     /*if (KdenliveSettings::osdtimecode()) {
660         mlt_properties_set_int( properties, "meta.attr.timecode", 1);
661         mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
662         m_osdInfo->set("dynamic", "1");
663         m_mltProducer->attach(*m_osdInfo);
664     }
665     else {
666         m_mltProducer->detach(*m_osdInfo);
667         m_osdInfo->set("dynamic", "0");
668     }*/
669     refresh();
670 }
671
672 void Render::setVolume(double volume) {
673     if (!m_mltConsumer || !m_mltProducer) return;
674     /*osdTimer->stop();
675     m_mltConsumer->set("refresh", 0);
676     // Attach filter for on screen display of timecode
677     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
678     mlt_properties_set_double( properties, "meta.volume", volume );
679     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
680     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
681
682     if (!KdenliveSettings::osdtimecode()) {
683     m_mltProducer->detach(*m_osdInfo);
684     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
685      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
686     }*/
687     refresh();
688     osdTimer->setSingleShot(2500);
689 }
690
691 void Render::slotOsdTimeout() {
692     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
693     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
694     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
695     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
696     refresh();
697 }
698
699 void Render::start() {
700     kDebug() << "-----  STARTING MONITOR: " << m_name;
701     if (m_winid == -1) {
702         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
703         return;
704     }
705
706     if (m_mltConsumer->is_stopped()) {
707         kDebug() << "-----  MONITOR: " << m_name << " WAS STOPPED";
708         if (m_mltConsumer->start() == -1) {
709             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."));
710             m_mltConsumer = NULL;
711             return;
712         } else {
713             kDebug() << "-----  MONITOR: " << m_name << " REFRESH";
714             refresh();
715         }
716     }
717     m_isBlocked = false;
718 }
719
720 void Render::clear() {
721     if (m_mltConsumer) {
722         m_mltConsumer->set("refresh", 0);
723         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
724     }
725
726     if (m_mltProducer) {
727         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
728         m_mltProducer->set_speed(0.0);
729         delete m_mltProducer;
730         m_mltProducer = NULL;
731         emit stopped();
732     }
733 }
734
735 void Render::stop() {
736     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
737         kDebug() << "/////////////   RENDER STOPPED: " << m_name;
738         m_mltConsumer->set("refresh", 0);
739         m_mltConsumer->stop();
740     }
741     kDebug() << "/////////////   RENDER STOP2-------";
742     m_isBlocked = true;
743
744     if (m_mltProducer) {
745         m_mltProducer->set_speed(0.0);
746         m_mltProducer->set("out", m_mltProducer->get_length() - 1);
747         kDebug() << m_mltProducer->get_length();
748     }
749     kDebug() << "/////////////   RENDER STOP3-------";
750 }
751
752 void Render::stop(const GenTime & startTime) {
753     kDebug() << "/////////////   RENDER STOP-------2";
754     if (m_mltProducer) {
755         m_mltProducer->set_speed(0.0);
756         m_mltProducer->seek((int) startTime.frames(m_fps));
757     }
758     m_mltConsumer->purge();
759 }
760
761 void Render::switchPlay() {
762     if (!m_mltProducer)
763         return;
764     if (m_mltProducer->get_speed() == 0.0) m_mltProducer->set_speed(1.0);
765     else {
766         m_mltProducer->set_speed(0.0);
767         kDebug() << "// POSITON: " << m_framePosition;
768         m_mltProducer->seek((int) m_framePosition);
769     }
770
771     /*if (speed == 0.0) {
772     m_mltProducer->seek((int) m_framePosition + 1);
773         m_mltConsumer->purge();
774     }*/
775     refresh();
776 }
777
778 void Render::play(double speed) {
779     if (!m_mltProducer)
780         return;
781     if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
782     m_mltProducer->set_speed(speed);
783     /*if (speed == 0.0) {
784     m_mltProducer->seek((int) m_framePosition + 1);
785         m_mltConsumer->purge();
786     }*/
787     refresh();
788 }
789
790 void Render::play(double speed, const GenTime & startTime) {
791     kDebug() << "/////////////   RENDER PLAY2-------" << speed;
792     if (!m_mltProducer)
793         return;
794     //m_mltProducer->set("out", m_mltProducer->get_length() - 1);
795     //if (speed == 0.0) m_mltConsumer->set("refresh", 0);
796     m_mltProducer->set_speed(speed);
797     m_mltProducer->seek((int)(startTime.frames(m_fps)));
798     //m_mltConsumer->purge();
799     //refresh();
800 }
801
802 void Render::play(double speed, const GenTime & startTime,
803                   const GenTime & stopTime) {
804     kDebug() << "/////////////   RENDER PLAY3-------" << speed << stopTime.frames(m_fps);
805     if (!m_mltProducer)
806         return;
807     m_mltProducer->set("out", stopTime.frames(m_fps));
808     m_mltProducer->seek((int)(startTime.frames(m_fps)));
809     m_mltConsumer->purge();
810     m_mltProducer->set_speed(speed);
811     refresh();
812 }
813
814
815 void Render::sendSeekCommand(GenTime time) {
816     if (!m_mltProducer)
817         return;
818     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
819     m_mltProducer->seek((int)(time.frames(m_fps)));
820     refresh();
821 }
822
823 void Render::seekToFrame(int pos) {
824     if (!m_mltProducer)
825         return;
826     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
827     m_mltProducer->seek(pos);
828     refresh();
829 }
830
831 void Render::askForRefresh() {
832     // Use a Timer so that we don't refresh too much
833     refreshTimer->start(200);
834 }
835
836 void Render::doRefresh() {
837     // Use a Timer so that we don't refresh too much
838     refresh();
839 }
840
841 void Render::refresh() {
842     if (!m_mltProducer || m_isBlocked)
843         return;
844     refreshTimer->stop();
845     if (m_mltConsumer) {
846         m_mltConsumer->set("refresh", 1);
847     }
848 }
849
850 /** Sets the description of this renderer to desc. */
851 void Render::setDescription(const QString & description) {
852     m_description = description;
853 }
854
855 /** Returns the description of this renderer */
856 QString Render::description() {
857     return m_description;
858 }
859
860
861 double Render::playSpeed() {
862     if (m_mltProducer) return m_mltProducer->get_speed();
863     return 0.0;
864 }
865
866 GenTime Render::seekPosition() const {
867     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
868     else return GenTime();
869 }
870
871
872 const QString & Render::rendererName() const {
873     return m_name;
874 }
875
876
877 void Render::emitFrameNumber(double position) {
878     //kDebug()<<"// POSITON: "<<m_framePosition;
879     if (m_generateScenelist) return;
880     m_framePosition = position;
881     emit rendererPosition((int) position);
882     //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent( GenTime((int) position, m_fps), m_monitorId));
883 }
884
885 void Render::emitConsumerStopped() {
886     // This is used to know when the playing stopped
887     if (m_mltProducer && !m_generateScenelist) {
888         double pos = m_mltProducer->position();
889         emit rendererStopped((int) pos);
890         //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent(GenTime((int) pos, m_fps), m_monitorId + 100));
891         //new QCustomEvent(10002));
892     }
893 }
894
895
896
897 void Render::exportFileToFirewire(QString srcFileName, int port, GenTime startTime, GenTime endTime) {
898     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
899 }
900
901
902 void Render::exportCurrentFrame(KUrl url, bool notify) {
903     if (!m_mltProducer) {
904         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
905         return;
906     }
907
908     int height = 1080;//KdenliveSettings::defaultheight();
909     int width = 1940; //KdenliveSettings::displaywidth();
910     QPixmap pix = KThumb::getFrame(m_mltProducer, -1, width, height);
911     /*
912        QPixmap pix(width, height);
913        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
914        m_convert.set("forced", mlt_image_rgb24a);
915        m_mltProducer->attach(m_convert);
916        Mlt::Frame * frame = m_mltProducer->get_frame();
917        m_mltProducer->detach(m_convert);
918        if (frame) {
919            pix = frameThumbnail(frame, width, height);
920            delete frame;
921        }*/
922     pix.save(url.path(), "PNG");
923     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
924 }
925
926 /** MLT PLAYLIST DIRECT MANIPULATON  **/
927
928
929 void Render::mltCheckLength(bool reload) {
930     //kDebug()<<"checking track length: "<<track<<"..........";
931
932     Mlt::Service service(m_mltProducer->get_service());
933     Mlt::Tractor tractor(service);
934
935     int trackNb = tractor.count();
936     double duration = 0;
937     double trackDuration;
938     if (trackNb == 1) {
939         Mlt::Producer trackProducer(tractor.track(0));
940         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
941         duration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
942         m_mltProducer->set("out", duration);
943         emit durationChanged((int) duration);
944         return;
945     }
946     while (trackNb > 1) {
947         Mlt::Producer trackProducer(tractor.track(trackNb - 1));
948         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
949         trackDuration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
950
951         kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
952         if (trackDuration > duration) duration = trackDuration;
953         trackNb--;
954     }
955
956     Mlt::Producer blackTrackProducer(tractor.track(0));
957     Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
958     double blackDuration = Mlt::Producer(blackTrackPlaylist.get_producer()).get_playtime() - 1;
959     kDebug() << " / / /DURATON FOR TRACK 0 = " << blackDuration;
960     if (blackDuration != duration) {
961         blackTrackPlaylist.remove_region(0, (int)blackDuration);
962         int i = 0;
963         int dur = (int)duration;
964         QDomDocument doc;
965         QDomElement black = doc.createElement("producer");
966         black.setAttribute("mlt_service", "colour");
967         black.setAttribute("colour", "black");
968         black.setAttribute("in", "0");
969         black.setAttribute("out", "13999");
970         while (dur > 14000) { // <producer mlt_service=\"colour\" colour=\"black\" in=\"0\" out=\"13999\" />
971             mltInsertClip(0, GenTime(i * 14000, m_fps), black);
972             dur = dur - 14000;
973             i++;
974         }
975         black.setAttribute("out", QString::number(dur));
976         mltInsertClip(0, GenTime(), black);
977
978         m_mltProducer->set("out", duration);
979         emit durationChanged((int)duration);
980     }
981 }
982
983 void Render::mltInsertClip(int track, GenTime position, QDomElement element) {
984     if (!m_mltProducer) {
985         kDebug() << "PLAYLIST NOT INITIALISED //////";
986         return;
987     }
988     Mlt::Producer parentProd(m_mltProducer->parent());
989     if (parentProd.get_producer() == NULL) {
990         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
991         return;
992     }
993     Mlt::Service service(parentProd.get_service());
994     Mlt::Tractor tractor(service);
995
996     Mlt::Producer trackProducer(tractor.track(track));
997     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
998
999     QDomDocument doc;
1000     doc.appendChild(doc.importNode(element, true));
1001     QString resource = doc.toString();
1002     char *tmp = decodedString(resource);
1003     Mlt::Producer clip(*m_mltProfile, "westley-xml", tmp);
1004     //clip.set_in_and_out(in.frames(m_fps), out.frames(m_fps));
1005     delete[] tmp;
1006
1007     trackPlaylist.insert_at((int) position.frames(m_fps), clip, 1);
1008     if (track != 0) mltCheckLength();
1009     tractor.multitrack()->refresh();
1010     tractor.refresh();
1011 }
1012
1013 void Render::mltCutClip(int track, GenTime position) {
1014     m_isBlocked = true;
1015
1016     Mlt::Service service(m_mltProducer->parent().get_service());
1017     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1018
1019     Mlt::Tractor tractor(service);
1020     Mlt::Producer trackProducer(tractor.track(track));
1021     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1022     trackPlaylist.split_at((int) position.frames(m_fps));
1023     trackPlaylist.consolidate_blanks(0);
1024     m_isBlocked = false;
1025 }
1026
1027 void Render::mltUpdateClip(int track, GenTime position, QDomElement element) {
1028     // TODO: optimize
1029     mltRemoveClip(track, position);
1030     mltInsertClip(track, position, element);
1031 }
1032
1033
1034 void Render::mltRemoveClip(int track, GenTime position) {
1035     m_isBlocked = true;
1036
1037     Mlt::Service service(m_mltProducer->parent().get_service());
1038     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1039
1040     Mlt::Tractor tractor(service);
1041     Mlt::Producer trackProducer(tractor.track(track));
1042     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1043     int clipIndex = trackPlaylist.get_clip_index_at((int) position.frames(m_fps));
1044     trackPlaylist.replace_with_blank(clipIndex);
1045     trackPlaylist.consolidate_blanks(0);
1046     if (track != 0) mltCheckLength();
1047     //emit durationChanged();
1048     m_isBlocked = false;
1049 }
1050
1051 void Render::mltRemoveEffect(int track, GenTime position, QString index, bool doRefresh) {
1052
1053     Mlt::Service service(m_mltProducer->parent().get_service());
1054
1055     Mlt::Tractor tractor(service);
1056     Mlt::Producer trackProducer(tractor.track(track));
1057     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1058     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1059     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1060     if (!clip) {
1061         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
1062         return;
1063     }
1064     Mlt::Service clipService(clip->get_service());
1065 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1066     m_isBlocked = true;
1067     int ct = 0;
1068     Mlt::Filter *filter = clipService.filter(ct);
1069     while (filter) {
1070         if (index == "-1" || filter->get("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
1071             clipService.detach(*filter);
1072             kDebug() << " / / / DLEETED EFFECT: " << ct;
1073         } else ct++;
1074         filter = clipService.filter(ct);
1075     }
1076     m_isBlocked = false;
1077     if (doRefresh) refresh();
1078 }
1079
1080
1081 void Render::mltAddEffect(int track, GenTime position, QMap <QString, QString> args, bool doRefresh) {
1082
1083     Mlt::Service service(m_mltProducer->parent().get_service());
1084
1085     Mlt::Tractor tractor(service);
1086     Mlt::Producer trackProducer(tractor.track(track));
1087     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1088
1089     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1090
1091     if (!clip) {
1092         kDebug() << "**********  CANNOT FIND CLIP TO APPLY EFFECT-----------";
1093         return;
1094     }
1095     Mlt::Service clipService(clip->get_service());
1096     m_isBlocked = true;
1097     // create filter
1098     QString tag = args.value("tag");
1099     //kDebug()<<" / / INSERTING EFFECT: "<<id;
1100     if (tag.startsWith("ladspa")) tag = "ladspa";
1101     char *filterId = decodedString(tag);
1102     Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterId);
1103     if (filter && filter->is_valid())
1104         filter->set("kdenlive_id", filterId);
1105     else {
1106         kDebug() << "filter is NULL";
1107         m_isBlocked = false;
1108         return;
1109     }
1110
1111     QMap<QString, QString>::Iterator it;
1112     QString keyFrameNumber = "#0";
1113
1114     for (it = args.begin(); it != args.end(); ++it) {
1115         //kDebug()<<" / / INSERTING EFFECT ARGS: "<<it.key()<<": "<<it.data();
1116         QString key;
1117         QString currentKeyFrameNumber;
1118         if (it.key().startsWith("#")) {
1119             currentKeyFrameNumber = it.key().section(":", 0, 0);
1120             if (currentKeyFrameNumber != keyFrameNumber) {
1121                 // attach filter to the clip
1122                 clipService.attach(*filter);
1123                 filter = new Mlt::Filter(*m_mltProfile, filterId);
1124                 filter->set("kdenlive_id", filterId);
1125                 keyFrameNumber = currentKeyFrameNumber;
1126             }
1127             key = it.key().section(":", 1);
1128         } else key = it.key();
1129         char *name = decodedString(key);
1130         char *value = decodedString(it.value());
1131         filter->set(name, value);
1132         delete[] name;
1133         delete[] value;
1134     }
1135     // attach filter to the clip
1136     clipService.attach(*filter);
1137     delete[] filterId;
1138     m_isBlocked = false;
1139     if (doRefresh) refresh();
1140 }
1141
1142 void Render::mltEditEffect(int track, GenTime position, QMap <QString, QString> args) {
1143     QString index = args.value("kdenlive_ix");
1144     QString tag =  args.value("tag");
1145     QMap<QString, QString>::Iterator it = args.begin();
1146     if (it.key().startsWith("#") || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
1147         // This is a keyframe effect, to edit it, we remove it and re-add it.
1148         mltRemoveEffect(track, position, index);
1149         mltAddEffect(track, position, args);
1150         return;
1151     }
1152
1153     // create filter
1154     Mlt::Service service(m_mltProducer->parent().get_service());
1155
1156     Mlt::Tractor tractor(service);
1157     Mlt::Producer trackProducer(tractor.track(track));
1158     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1159     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1160     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1161     if (!clip) {
1162         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1163         return;
1164     }
1165     Mlt::Service clipService(clip->get_service());
1166     m_isBlocked = true;
1167     int ct = 0;
1168     Mlt::Filter *filter = clipService.filter(ct);
1169     while (filter) {
1170         if (filter->get("kdenlive_ix") == index) {
1171             break;
1172         }
1173         ct++;
1174         filter = clipService.filter(ct);
1175     }
1176
1177
1178     if (!filter) {
1179         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT!!!!!";
1180         // filter was not found, it was probably a disabled filter, so add it to the correct place...
1181         int ct = 0;
1182         filter = clipService.filter(ct);
1183         QList <Mlt::Filter *> filtersList;
1184         while (filter) {
1185             if (QString(filter->get("kdenlive_ix")).toInt() > index.toInt()) {
1186                 filtersList.append(filter);
1187                 clipService.detach(*filter);
1188             } else ct++;
1189             filter = clipService.filter(ct);
1190         }
1191         mltAddEffect(track, position, args);
1192
1193         for (int i = 0; i < filtersList.count(); i++) {
1194             clipService.attach(*(filtersList.at(i)));
1195         }
1196
1197         m_isBlocked = false;
1198         return;
1199     }
1200
1201     for (it = args.begin(); it != args.end(); ++it) {
1202         kDebug() << " / / EDITING EFFECT ARGS: " << it.key() << ": " << it.value();
1203         char *name = decodedString(it.key());
1204         char *value = decodedString(it.value());
1205         filter->set(name, value);
1206         delete[] name;
1207         delete[] value;
1208     }
1209     m_isBlocked = false;
1210     refresh();
1211 }
1212
1213 void Render::mltMoveEffect(int track, GenTime position, int oldPos, int newPos) {
1214
1215     kDebug() << "MOVING EFFECT FROM " << oldPos<< ", TO: " << newPos;
1216     Mlt::Service service(m_mltProducer->parent().get_service());
1217
1218     Mlt::Tractor tractor(service);
1219     Mlt::Producer trackProducer(tractor.track(track));
1220     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1221     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1222     Mlt::Producer *clip = trackPlaylist.get_clip_at((int) position.frames(m_fps));
1223     if (!clip) {
1224         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1225         return;
1226     }
1227     Mlt::Service clipService(clip->get_service());
1228     m_isBlocked = true;
1229     int ct = 0;
1230     QList <Mlt::Filter *> filtersList;
1231     Mlt::Filter *filter = clipService.filter(ct);
1232     bool found = false;
1233     if (newPos > oldPos) {
1234         while (filter) {
1235             if (!found && QString(filter->get("kdenlive_ix")).toInt() == oldPos) {
1236                 filter->set("kdenlive_ix", newPos);
1237                 filtersList.append(filter);
1238                 clipService.detach(*filter);
1239                 filter = clipService.filter(ct);
1240                 while (filter && QString(filter->get("kdenlive_ix")).toInt() <= newPos) {
1241                     filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() - 1);
1242                     ct++;
1243                     filter = clipService.filter(ct);
1244                 }
1245                 found = true;
1246             }
1247             if (filter && QString(filter->get("kdenlive_ix")).toInt() > newPos) {
1248                 filtersList.append(filter);
1249                 clipService.detach(*filter);
1250             } else ct++;
1251             filter = clipService.filter(ct);
1252         }
1253     }
1254     else {
1255         while (filter) {
1256             if (QString(filter->get("kdenlive_ix")).toInt() == oldPos) {
1257                 filter->set("kdenlive_ix", newPos);
1258                 filtersList.append(filter);
1259                 clipService.detach(*filter);
1260             } else ct++;
1261             filter = clipService.filter(ct);
1262         }
1263
1264         ct = 0;
1265         filter = clipService.filter(ct);
1266         while (filter) {
1267             int pos = QString(filter->get("kdenlive_ix")).toInt();
1268             if (pos >= newPos) {
1269                 if (pos < oldPos) filter->set("kdenlive_ix", QString(filter->get("kdenlive_ix")).toInt() + 1);
1270                 filtersList.append(filter);
1271                 clipService.detach(*filter);
1272             } else ct++;
1273             filter = clipService.filter(ct);
1274         }
1275     }
1276     
1277     for (int i = 0; i < filtersList.count(); i++) {
1278         clipService.attach(*(filtersList.at(i)));
1279     }
1280
1281     m_isBlocked = false;
1282     refresh();
1283 }
1284
1285 void Render::mltResizeClipEnd(int track, GenTime pos, GenTime in, GenTime out) {
1286     m_isBlocked = true;
1287
1288     Mlt::Service service(m_mltProducer->parent().get_service());
1289
1290     Mlt::Tractor tractor(service);
1291     Mlt::Producer trackProducer(tractor.track(track));
1292     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1293     if (trackPlaylist.is_blank_at((int) pos.frames(m_fps) + 1))
1294         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1295     int clipIndex = trackPlaylist.get_clip_index_at((int) pos.frames(m_fps) + 1);
1296
1297     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;
1298     int newDuration = (int) out.frames(m_fps) - 1;
1299
1300     kDebug() << " ** RESIZING CLIP END:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", in: " << in.frames(25) << ", out: " << out.frames(25) << ", PREVIOUS duration: " << previousDuration;
1301     trackPlaylist.resize_clip(clipIndex, (int) in.frames(m_fps), newDuration);
1302     trackPlaylist.consolidate_blanks(0);
1303     if (previousDuration < newDuration) {
1304         // clip was made longer, trim next blank if there is one.
1305         if (trackPlaylist.is_blank(clipIndex + 1)) {
1306             trackPlaylist.split(clipIndex + 1, newDuration - previousDuration);
1307             trackPlaylist.remove(clipIndex + 1);
1308         }
1309     } else trackPlaylist.insert_blank(clipIndex + 1, previousDuration - newDuration - 1);
1310
1311     trackPlaylist.consolidate_blanks(0);
1312     tractor.multitrack()->refresh();
1313     tractor.refresh();
1314     if (track != 0) mltCheckLength();
1315     m_isBlocked = false;
1316 }
1317
1318 void Render::mltChangeTrackState(int track, bool mute, bool blind) {
1319     Mlt::Service service(m_mltProducer->parent().get_service());
1320     Mlt::Tractor tractor(service);
1321     Mlt::Producer trackProducer(tractor.track(track));
1322     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1323     if (mute) {
1324         if (blind) trackProducer.set("hide", 3);
1325         else trackProducer.set("hide", 2);
1326     } else if (blind) {
1327         trackProducer.set("hide", 1);
1328     } else {
1329         trackProducer.set("hide", 0);
1330     }
1331     tractor.multitrack()->refresh();
1332     tractor.refresh();
1333     refresh();
1334 }
1335
1336 void Render::mltResizeClipStart(int track, GenTime pos, GenTime moveEnd, GenTime moveStart, GenTime in, GenTime out) {
1337     m_isBlocked = true;
1338
1339     Mlt::Service service(m_mltProducer->parent().get_service());
1340
1341     int moveFrame = (int)(moveEnd - moveStart).frames(m_fps);
1342
1343     Mlt::Tractor tractor(service);
1344     Mlt::Producer trackProducer(tractor.track(track));
1345     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1346     if (trackPlaylist.is_blank_at((int) pos.frames(m_fps) - 1))
1347         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1348     int clipIndex = trackPlaylist.get_clip_index_at((int) pos.frames(m_fps) - 1);
1349     kDebug() << " ** RESIZING CLIP START:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", moving: " << moveFrame << ", in: " << in.frames(25) << ", out: " << out.frames(25);
1350
1351     trackPlaylist.resize_clip(clipIndex, (int) in.frames(m_fps), (int) out.frames(m_fps));
1352     if (moveFrame > 0) trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
1353     else {
1354         int midpos = (int)moveStart.frames(m_fps) - 1; //+ (moveFrame / 2)
1355         int blankIndex = trackPlaylist.get_clip_index_at(midpos);
1356         int blankLength = trackPlaylist.clip_length(blankIndex);
1357
1358         kDebug() << " + resizing blank: " << blankIndex << ", Mid: " << midpos << ", Length: " << blankLength << ", SIZE DIFF: " << moveFrame;
1359
1360         if (blankLength + moveFrame == 0) trackPlaylist.remove(blankIndex);
1361         else trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
1362     }
1363     trackPlaylist.consolidate_blanks(0);
1364     m_isBlocked = false;
1365 }
1366
1367 void Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd) {
1368     mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps));
1369 }
1370
1371
1372 void Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd) {
1373     m_isBlocked = true;
1374
1375     m_mltConsumer->set("refresh", 0);
1376
1377     Mlt::Service service(m_mltProducer->parent().get_service());
1378     if (service.type() != tractor_type) kWarning() << "// TRACTOR PROBLEM";
1379
1380     Mlt::Tractor tractor(service);
1381     Mlt::Producer trackProducer(tractor.track(startTrack));
1382     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1383     int clipIndex = trackPlaylist.get_clip_index_at(moveStart + 1);
1384
1385     Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
1386     trackPlaylist.consolidate_blanks(0);
1387     //mlt_events_block( MLT_PRODUCER_PROPERTIES(clipProducer.get_producer()), NULL );
1388
1389     if (endTrack == startTrack) {
1390         if (!trackPlaylist.is_blank_at(moveEnd)) {
1391             kWarning() << "// ERROR, CLIP COLLISION----------";
1392             int ix = trackPlaylist.get_clip_index_at(moveEnd);
1393             kDebug() << "BAD CLIP STARTS AT: " << trackPlaylist.clip_start(ix) << ", LENGT: " << trackPlaylist.clip_length(ix);
1394         }
1395         trackPlaylist.insert_at(moveEnd, clipProducer, 1);
1396         trackPlaylist.consolidate_blanks(0);
1397     } else {
1398         trackPlaylist.consolidate_blanks(0);
1399         Mlt::Producer destTrackProducer(tractor.track(endTrack));
1400         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
1401         destTrackPlaylist.consolidate_blanks(1);
1402         destTrackPlaylist.insert_at(moveEnd, clipProducer, 1);
1403         destTrackPlaylist.consolidate_blanks(0);
1404     }
1405
1406     mltCheckLength();
1407     m_isBlocked = false;
1408     m_mltConsumer->set("refresh", 1);
1409     //mlt_events_unblock( MLT_PRODUCER_PROPERTIES(clipProducer.get_producer()), NULL );
1410 }
1411
1412 void Render::mltMoveTransition(QString type, int startTrack, int trackOffset, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut) {
1413     m_isBlocked = true;
1414     Mlt::Service service(m_mltProducer->parent().get_service());
1415     Mlt::Tractor tractor(service);
1416     Mlt::Field *field = tractor.field();
1417
1418     m_mltConsumer->set("refresh", 0);
1419     mlt_service serv = m_mltProducer->parent().get_service();
1420
1421     mlt_service nextservice = mlt_service_get_producer(serv);
1422     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1423     QString mlt_type = mlt_properties_get(properties, "mlt_type");
1424     QString resource = mlt_properties_get(properties, "mlt_service");
1425     int old_pos = (int)(oldIn.frames(m_fps) + oldOut.frames(m_fps)) / 2;
1426
1427     int new_in = (int)newIn.frames(m_fps);
1428     int new_out = (int)newOut.frames(m_fps) - 1;
1429
1430     while (mlt_type == "transition") {
1431         mlt_transition tr = (mlt_transition) nextservice;
1432         int currentTrack = mlt_transition_get_b_track(tr);
1433         int currentIn = (int) mlt_transition_get_in(tr);
1434         int currentOut = (int) mlt_transition_get_out(tr);
1435
1436         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
1437             mlt_transition_set_in_and_out(tr, new_in, new_out);
1438             if (trackOffset != 0) {
1439                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
1440                 mlt_properties_set_int(properties, "a_track", mlt_transition_get_a_track(tr) + trackOffset);
1441                 mlt_properties_set_int(properties, "b_track", mlt_transition_get_b_track(tr) + trackOffset);
1442                 //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);
1443             }
1444
1445             break;
1446         }
1447         nextservice = mlt_service_producer(nextservice);
1448         properties = MLT_SERVICE_PROPERTIES(nextservice);
1449         mlt_type = mlt_properties_get(properties, "mlt_type");
1450         resource = mlt_properties_get(properties, "mlt_service");
1451     }
1452     m_isBlocked = false;
1453     m_mltConsumer->set("refresh", 1);
1454 }
1455
1456 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
1457     //kDebug() << "update transition"  << tag;
1458     if (oldTag == tag) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
1459     else {
1460         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
1461         mltAddTransition(tag, a_track, b_track, in, out, xml);
1462     }
1463     mltSavePlaylist();
1464 }
1465
1466 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
1467     m_isBlocked = true;
1468
1469     Mlt::Service service(m_mltProducer->parent().get_service());
1470     Mlt::Tractor tractor(service);
1471     Mlt::Field *field = tractor.field();
1472
1473     m_mltConsumer->set("refresh", 0);
1474     mlt_service serv = m_mltProducer->parent().get_service();
1475
1476     mlt_service nextservice = mlt_service_get_producer(serv);
1477     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1478     QString mlt_type = mlt_properties_get(properties, "mlt_type");
1479     QString resource = mlt_properties_get(properties, "mlt_service");
1480     int in_pos = (int) in.frames(m_fps);
1481     int out_pos = (int) out.frames(m_fps);
1482
1483     while (mlt_type == "transition") {
1484         mlt_transition tr = (mlt_transition) nextservice;
1485         int currentTrack = mlt_transition_get_b_track(tr);
1486         int currentIn = (int) mlt_transition_get_in(tr);
1487         int currentOut = (int) mlt_transition_get_out(tr);
1488
1489         if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
1490             QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
1491             QMap<QString, QString>::Iterator it;
1492             QString key;
1493             mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
1494
1495             for (it = map.begin(); it != map.end(); ++it) {
1496                 key = it.key();
1497                 char *name = decodedString(key);
1498                 char *value = decodedString(it.value());
1499                 mlt_properties_set(transproperties, name, value);
1500                 kDebug() << " ------  UPDATING TRANS PARAM: " << name << ": " << value;
1501                 //filter->set("kdenlive_id", id);
1502                 delete[] name;
1503                 delete[] value;
1504             }
1505             break;
1506         }
1507         nextservice = mlt_service_producer(nextservice);
1508         properties = MLT_SERVICE_PROPERTIES(nextservice);
1509         mlt_type = mlt_properties_get(properties, "mlt_type");
1510         resource = mlt_properties_get(properties, "mlt_service");
1511     }
1512     m_isBlocked = false;
1513     m_mltConsumer->set("refresh", 1);
1514 }
1515
1516 void Render::mltDeleteTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
1517
1518     Mlt::Service service(m_mltProducer->parent().get_service());
1519     Mlt::Tractor tractor(service);
1520     Mlt::Field *field = tractor.field();
1521
1522     m_mltConsumer->set("refresh", 0);
1523     mlt_service serv = m_mltProducer->parent().get_service();
1524
1525     mlt_service nextservice = mlt_service_get_producer(serv);
1526     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1527     QString mlt_type = mlt_properties_get(properties, "mlt_type");
1528     QString resource = mlt_properties_get(properties, "mlt_service");
1529     int old_pos = (int)((in + out).frames(m_fps) / 2);
1530
1531     while (mlt_type == "transition") {
1532         mlt_transition tr = (mlt_transition) nextservice;
1533         int currentTrack = mlt_transition_get_b_track(tr);
1534         int currentIn = (int) mlt_transition_get_in(tr);
1535         int currentOut = (int) mlt_transition_get_out(tr);
1536         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
1537
1538         if (resource == tag && b_track == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
1539             mlt_field_disconnect_service(field->get_field(), nextservice);
1540             break;
1541         }
1542         nextservice = mlt_service_producer(nextservice);
1543         properties = MLT_SERVICE_PROPERTIES(nextservice);
1544         mlt_type = mlt_properties_get(properties, "mlt_type");
1545         resource = mlt_properties_get(properties, "mlt_service");
1546     }
1547     m_mltConsumer->set("refresh", 1);
1548 }
1549
1550 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml) {
1551     QDomNodeList attribs = xml.elementsByTagName("parameter");
1552     QMap<QString, QString> map;
1553     for (int i = 0;i < attribs.count();i++) {
1554         QDomElement e = attribs.item(i).toElement();
1555         QString name = e.attribute("name");
1556         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
1557         map[name] = e.attribute("default");
1558         if (!e.attribute("value").isEmpty()) {
1559             map[name] = e.attribute("value");
1560         }
1561         if (!e.attribute("factor").isEmpty() && e.attribute("factor").toDouble() > 0) {
1562             map[name] = QString::number(map[name].toDouble() / e.attribute("factor").toDouble());
1563             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
1564         }
1565
1566         if (e.attribute("namedesc").contains(";")) {
1567             QString format = e.attribute("format");
1568             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1569             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1570             QString neu;
1571             QTextStream txtNeu(&neu);
1572             if (values.size() > 0)
1573                 txtNeu << (int)values[0].toDouble();
1574             int i = 0;
1575             for (i = 0;i < separators.size() && i + 1 < values.size();i++) {
1576                 txtNeu << separators[i];
1577                 txtNeu << (int)(values[i+1].toDouble());
1578             }
1579             if (i < separators.size())
1580                 txtNeu << separators[i];
1581             map[e.attribute("name")] = neu;
1582         }
1583
1584     }
1585     return map;
1586 }
1587
1588 void Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
1589     //kDebug() << "-- ADDING TRANSITION: " << tag << ", ON TRACKS: " << a_track << ", " << b_track;
1590     QMap<QString, QString> args = mltGetTransitionParamsFromXml(xml);
1591
1592
1593     Mlt::Service service(m_mltProducer->parent().get_service());
1594
1595     Mlt::Tractor tractor(service);
1596     Mlt::Field *field = tractor.field();
1597
1598     char *transId = decodedString(tag);
1599     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, transId);
1600     transition->set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps));
1601     QMap<QString, QString>::Iterator it;
1602     QString key;
1603
1604     kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
1605
1606     for (it = args.begin(); it != args.end(); ++it) {
1607         key = it.key();
1608         char *name = decodedString(key);
1609         char *value = decodedString(it.value());
1610         transition->set(name, value);
1611         kDebug() << " ------  ADDING TRANS PARAM: " << name << ": " << value;
1612         //filter->set("kdenlive_id", id);
1613         delete[] name;
1614         delete[] value;
1615     }
1616     // attach filter to the clip
1617     field->plant_transition(*transition, a_track, b_track);
1618     delete[] transId;
1619     refresh();
1620 }
1621
1622 void Render::mltSavePlaylist() {
1623     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
1624     Mlt::Consumer fileConsumer(*m_mltProfile, "westley");
1625     fileConsumer.set("resource", "/tmp/playlist.westley");
1626
1627     Mlt::Service service(m_mltProducer->get_service());
1628
1629     fileConsumer.connect(service);
1630     fileConsumer.start();
1631
1632 }
1633
1634 #include "renderer.moc"
1635