]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
several updates for slideshow clips
[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 addedXml) {
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     westleyConsumer.start();
609     if (!addedXml.isNull()) {
610         // add Kdenlive specific tags
611         QFile file(path);
612         QDomDocument doc;
613         //doc.setContent(&file, false);
614         doc.appendChild(doc.importNode(addedXml, true));
615         file.close();
616         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
617             kWarning() << "//////  ERROR writing to file: " << path;
618             return;
619         }
620         QTextStream out(&file);
621         out << doc.toString();
622         file.close();
623     }
624 }
625
626
627 const double Render::fps() const {
628     return m_fps;
629 }
630
631 void Render::connectPlaylist() {
632     if (!m_mltConsumer) return;
633     m_connectTimer->stop();
634     m_mltConsumer->set("refresh", "0");
635     m_mltConsumer->connect(*m_mltProducer);
636     m_mltProducer->set_speed(0.0);
637     m_mltConsumer->start();
638     refresh();
639     /*
640      if (m_mltConsumer->start() == -1) {
641           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."));
642           m_mltConsumer = NULL;
643      }
644      else {
645              refresh();
646      }*/
647 }
648
649 void Render::refreshDisplay() {
650
651     if (!m_mltProducer) return;
652     m_mltConsumer->set("refresh", 0);
653
654     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
655     /*if (KdenliveSettings::osdtimecode()) {
656         mlt_properties_set_int( properties, "meta.attr.timecode", 1);
657         mlt_properties_set( properties, "meta.attr.timecode.markup", "#timecode#");
658         m_osdInfo->set("dynamic", "1");
659         m_mltProducer->attach(*m_osdInfo);
660     }
661     else {
662         m_mltProducer->detach(*m_osdInfo);
663         m_osdInfo->set("dynamic", "0");
664     }*/
665     refresh();
666 }
667
668 void Render::setVolume(double volume) {
669     if (!m_mltConsumer || !m_mltProducer) return;
670     /*osdTimer->stop();
671     m_mltConsumer->set("refresh", 0);
672     // Attach filter for on screen display of timecode
673     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
674     mlt_properties_set_double( properties, "meta.volume", volume );
675     mlt_properties_set_int( properties, "meta.attr.osdvolume", 1);
676     mlt_properties_set( properties, "meta.attr.osdvolume.markup", i18n("Volume: ") + QString::number(volume * 100));
677
678     if (!KdenliveSettings::osdtimecode()) {
679     m_mltProducer->detach(*m_osdInfo);
680     mlt_properties_set_int( properties, "meta.attr.timecode", 0);
681      if (m_mltProducer->attach(*m_osdInfo) == 1) kDebug()<<"////// error attaching filter";
682     }*/
683     refresh();
684     osdTimer->setSingleShot(2500);
685 }
686
687 void Render::slotOsdTimeout() {
688     mlt_properties properties = MLT_PRODUCER_PROPERTIES(m_mltProducer->get_producer());
689     mlt_properties_set_int(properties, "meta.attr.osdvolume", 0);
690     mlt_properties_set(properties, "meta.attr.osdvolume.markup", NULL);
691     //if (!KdenliveSettings::osdtimecode()) m_mltProducer->detach(*m_osdInfo);
692     refresh();
693 }
694
695 void Render::start() {
696     kDebug() << "-----  STARTING MONITOR: " << m_name;
697     if (m_winid == -1) {
698         kDebug() << "-----  BROKEN MONITOR: " << m_name << ", RESTART";
699         return;
700     }
701
702     if (m_mltConsumer->is_stopped()) {
703         kDebug() << "-----  MONITOR: " << m_name << " WAS STOPPED";
704         if (m_mltConsumer->start() == -1) {
705             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."));
706             m_mltConsumer = NULL;
707             return;
708         } else {
709             kDebug() << "-----  MONITOR: " << m_name << " REFRESH";
710             refresh();
711         }
712     }
713     m_isBlocked = false;
714 }
715
716 void Render::clear() {
717     if (m_mltConsumer) {
718         m_mltConsumer->set("refresh", 0);
719         if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
720     }
721
722     if (m_mltProducer) {
723         //if (KdenliveSettings::osdtimecode() && m_osdInfo) m_mltProducer->detach(*m_osdInfo);
724         m_mltProducer->set_speed(0.0);
725         delete m_mltProducer;
726         m_mltProducer = NULL;
727         emit stopped();
728     }
729 }
730
731 void Render::stop() {
732     if (m_mltConsumer && !m_mltConsumer->is_stopped()) {
733         kDebug() << "/////////////   RENDER STOPPED: " << m_name;
734         m_mltConsumer->set("refresh", 0);
735         m_mltConsumer->stop();
736     }
737     kDebug() << "/////////////   RENDER STOP2-------";
738     m_isBlocked = true;
739
740     if (m_mltProducer) {
741         m_mltProducer->set_speed(0.0);
742         m_mltProducer->set("out", m_mltProducer->get_length() - 1);
743         kDebug() << m_mltProducer->get_length();
744     }
745     kDebug() << "/////////////   RENDER STOP3-------";
746 }
747
748 void Render::stop(const GenTime & startTime) {
749     kDebug() << "/////////////   RENDER STOP-------2";
750     if (m_mltProducer) {
751         m_mltProducer->set_speed(0.0);
752         m_mltProducer->seek((int) startTime.frames(m_fps));
753     }
754     m_mltConsumer->purge();
755 }
756
757 void Render::switchPlay() {
758     if (!m_mltProducer)
759         return;
760     if (m_mltProducer->get_speed() == 0.0) m_mltProducer->set_speed(1.0);
761     else {
762         m_mltProducer->set_speed(0.0);
763         kDebug() << "// POSITON: " << m_framePosition;
764         m_mltProducer->seek((int) m_framePosition);
765     }
766
767     /*if (speed == 0.0) {
768     m_mltProducer->seek((int) m_framePosition + 1);
769         m_mltConsumer->purge();
770     }*/
771     refresh();
772 }
773
774 void Render::play(double speed) {
775     if (!m_mltProducer)
776         return;
777     if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
778     m_mltProducer->set_speed(speed);
779     /*if (speed == 0.0) {
780     m_mltProducer->seek((int) m_framePosition + 1);
781         m_mltConsumer->purge();
782     }*/
783     refresh();
784 }
785
786 void Render::play(double speed, const GenTime & startTime) {
787     kDebug() << "/////////////   RENDER PLAY2-------" << speed;
788     if (!m_mltProducer)
789         return;
790     //m_mltProducer->set("out", m_mltProducer->get_length() - 1);
791     //if (speed == 0.0) m_mltConsumer->set("refresh", 0);
792     m_mltProducer->set_speed(speed);
793     m_mltProducer->seek((int)(startTime.frames(m_fps)));
794     //m_mltConsumer->purge();
795     //refresh();
796 }
797
798 void Render::play(double speed, const GenTime & startTime,
799                   const GenTime & stopTime) {
800     kDebug() << "/////////////   RENDER PLAY3-------" << speed << stopTime.frames(m_fps);
801     if (!m_mltProducer)
802         return;
803     m_mltProducer->set("out", stopTime.frames(m_fps));
804     m_mltProducer->seek((int)(startTime.frames(m_fps)));
805     m_mltConsumer->purge();
806     m_mltProducer->set_speed(speed);
807     refresh();
808 }
809
810
811 void Render::sendSeekCommand(GenTime time) {
812     if (!m_mltProducer)
813         return;
814     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
815     m_mltProducer->seek((int)(time.frames(m_fps)));
816     refresh();
817 }
818
819 void Render::seekToFrame(int pos) {
820     if (!m_mltProducer)
821         return;
822     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
823     m_mltProducer->seek(pos);
824     refresh();
825 }
826
827 void Render::askForRefresh() {
828     // Use a Timer so that we don't refresh too much
829     refreshTimer->start(200);
830 }
831
832 void Render::doRefresh() {
833     // Use a Timer so that we don't refresh too much
834     refresh();
835 }
836
837 void Render::refresh() {
838     if (!m_mltProducer || m_isBlocked)
839         return;
840     refreshTimer->stop();
841     if (m_mltConsumer) {
842         m_mltConsumer->set("refresh", 1);
843     }
844 }
845
846 /** Sets the description of this renderer to desc. */
847 void Render::setDescription(const QString & description) {
848     m_description = description;
849 }
850
851 /** Returns the description of this renderer */
852 QString Render::description() {
853     return m_description;
854 }
855
856
857 double Render::playSpeed() {
858     if (m_mltProducer) return m_mltProducer->get_speed();
859     return 0.0;
860 }
861
862 GenTime Render::seekPosition() const {
863     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
864     else return GenTime();
865 }
866
867
868 const QString & Render::rendererName() const {
869     return m_name;
870 }
871
872
873 void Render::emitFrameNumber(double position) {
874     //kDebug()<<"// POSITON: "<<m_framePosition;
875     if (m_generateScenelist) return;
876     m_framePosition = position;
877     emit rendererPosition((int) position);
878     //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent( GenTime((int) position, m_fps), m_monitorId));
879 }
880
881 void Render::emitConsumerStopped() {
882     // This is used to know when the playing stopped
883     if (m_mltProducer && !m_generateScenelist) {
884         double pos = m_mltProducer->position();
885         emit rendererStopped((int) pos);
886         //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent(GenTime((int) pos, m_fps), m_monitorId + 100));
887         //new QCustomEvent(10002));
888     }
889 }
890
891
892
893 void Render::exportFileToFirewire(QString srcFileName, int port, GenTime startTime, GenTime endTime) {
894     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
895 }
896
897
898 void Render::exportCurrentFrame(KUrl url, bool notify) {
899     if (!m_mltProducer) {
900         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
901         return;
902     }
903
904     int height = 1080;//KdenliveSettings::defaultheight();
905     int width = 1940; //KdenliveSettings::displaywidth();
906     QPixmap pix = KThumb::getFrame(m_mltProducer, -1, width, height);
907     /*
908        QPixmap pix(width, height);
909        Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
910        m_convert.set("forced", mlt_image_rgb24a);
911        m_mltProducer->attach(m_convert);
912        Mlt::Frame * frame = m_mltProducer->get_frame();
913        m_mltProducer->detach(m_convert);
914        if (frame) {
915            pix = frameThumbnail(frame, width, height);
916            delete frame;
917        }*/
918     pix.save(url.path(), "PNG");
919     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
920 }
921
922 /** MLT PLAYLIST DIRECT MANIPULATON  **/
923
924
925 void Render::mltCheckLength(bool reload) {
926     //kDebug()<<"checking track length: "<<track<<"..........";
927
928     if (reload) {
929         //reinsert main tractorin playlist so that the producer can take the new length ( not automatic done)
930         Mlt::Service service(m_mltProducer->get_service());
931         Mlt::Playlist prod(service);
932         Mlt::Service service_playlist(prod.get_clip(0)->get_service());
933         Mlt::Producer producer_playlist(service_playlist);
934
935         Mlt::Tractor tr(producer_playlist.parent());
936         prod.remove(0);
937         prod.insert(tr, 0);
938     }
939     Mlt::Tractor *tractor = getTractor();
940
941     int trackNb = tractor->count();
942     double duration = 0;
943     double trackDuration = 0;
944     if (trackNb == 1) {
945         Mlt::Producer trackProducer(tractor->track(0));
946         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
947         duration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
948         kDebug() << trackNb << " " << duration;
949         m_mltProducer->set("out", duration);
950         emit durationChanged((int)duration);
951         return;
952     }
953     while (trackNb > 1) {
954         Mlt::Producer trackProducer(tractor->track(trackNb - 1));
955         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
956         trackDuration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
957
958         kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
959         if (trackDuration > duration) duration = trackDuration;
960         trackNb--;
961     }
962
963     Mlt::Producer blackTrackProducer(tractor->track(0));
964     Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
965     double blackDuration = Mlt::Producer(blackTrackPlaylist.get_producer()).get_playtime() - 1;
966     kDebug() << " / / /DURATON FOR TRACK 0 = " << blackDuration;
967     if (blackDuration != duration) {
968         blackTrackPlaylist.remove_region(0, (int)blackDuration);
969         int i = 0;
970         int dur = (int)duration;
971         QDomDocument doc;
972         QDomElement black = doc.createElement("producer");
973         black.setAttribute("mlt_service", "colour");
974         black.setAttribute("colour", "black");
975         black.setAttribute("in", "0");
976         black.setAttribute("out", "13999");
977         while (dur > 14000) { // <producer mlt_service=\"colour\" colour=\"black\" in=\"0\" out=\"13999\" />
978             mltInsertClip(0, GenTime(i * 14000, m_fps), black);
979             dur = dur - 14000;
980             i++;
981         }
982         black.setAttribute("out", QString::number(dur));
983         mltInsertClip(0, GenTime(), black);
984
985         m_mltProducer->set("out", duration);
986         emit durationChanged((int)duration);
987     }
988     if (tractor)
989         delete tractor;
990 }
991
992 Mlt::Tractor* Render::getTractor() {
993     Mlt::Service s1(m_mltProducer->get_service());
994     Mlt::Playlist pl(s1);
995     Mlt::Producer srv(pl.get_clip(0)->parent());
996     Mlt::Tractor *tractor = new Mlt::Tractor(srv);
997     return tractor;
998 }
999
1000 Mlt::Playlist* Render::getPlaylist(int track) {
1001     Mlt::Tractor *tractor = getTractor();
1002
1003     if (tractor) {
1004
1005         Mlt::Producer trackProducer(tractor->track(track));
1006         Mlt::Service playlistservice(trackProducer.get_service());
1007         delete tractor;
1008         return new Mlt::Playlist(playlistservice);
1009
1010     }
1011     return NULL;
1012
1013 }
1014 void Render::mltInsertClip(int track, GenTime position, QDomElement element) {
1015     if (!m_mltProducer) {
1016         kDebug() << "PLAYLIST NOT INITIALISED //////";
1017         return;
1018     }
1019     Mlt::Producer parentProd(m_mltProducer->parent());
1020     if (parentProd.get_producer() == NULL) {
1021         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
1022         return;
1023     }
1024     m_isBlocked = true;
1025     // Mlt::Service service(parentProd.get_service());
1026     //Mlt::Tractor tractor(service);
1027
1028     QDomDocument doc;
1029     doc.appendChild(doc.importNode(element, true));
1030     QString resource = doc.toString();
1031
1032     kDebug() << "///////  ADDING CLIP TMLNE: " << resource << " ON TRACK: " << track;
1033     //Mlt::Tractor *tractor = getTractor();
1034     //if (tractor) {
1035     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1036     if (trackPlaylist) {
1037         char *tmp = decodedString(resource);
1038         Mlt::Producer clip(*m_mltProfile, "westley-xml", tmp);
1039         //clip.set_in_and_out(in.frames(m_fps), out.frames(m_fps));
1040         delete[] tmp;
1041
1042         trackPlaylist->insert_at((int)position.frames(m_fps), clip, 1);
1043         //tractor->multitrack()->refresh();
1044         //tractor->refresh();
1045         if (track != 0) mltCheckLength();
1046
1047
1048
1049         delete trackPlaylist;
1050         mltSavePlaylist();
1051     }
1052     //delete tractor;
1053     //}
1054     m_isBlocked = false;
1055 }
1056
1057 void Render::mltCutClip(int track, GenTime position) {
1058     m_isBlocked = true;
1059     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1060     if (trackPlaylist) {
1061         trackPlaylist->split_at((int)position.frames(m_fps));
1062         trackPlaylist->consolidate_blanks(0);
1063         kDebug() << "/ / / /CUTTING CLIP AT: " << position.frames(m_fps);
1064         delete trackPlaylist;
1065     }
1066     m_isBlocked = false;
1067 }
1068
1069 void Render::mltUpdateClip(int track, GenTime position, QDomElement element) {
1070     // TODO: optimize
1071     mltRemoveClip(track, position);
1072     mltInsertClip(track, position, element);
1073 }
1074
1075
1076 void Render::mltRemoveClip(int track, GenTime position) {
1077     m_isBlocked = true;
1078     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1079     if (trackPlaylist) {
1080         int clipIndex = trackPlaylist->get_clip_index_at((int)position.frames(m_fps));
1081         //trackPlaylist.remove(clipIndex);
1082         trackPlaylist->replace_with_blank(clipIndex);
1083         trackPlaylist->consolidate_blanks(0);
1084         if (track != 0) mltCheckLength();
1085         delete trackPlaylist;
1086     }
1087     //emit durationChanged();
1088     m_isBlocked = false;
1089 }
1090
1091 void Render::mltRemoveEffect(int track, GenTime position, QString index, bool doRefresh) {
1092     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1093     if (trackPlaylist) {
1094         //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1095         Mlt::Producer *clip = trackPlaylist->get_clip_at((int)position.frames(m_fps));
1096         if (!clip) {
1097             kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
1098             return;
1099         }
1100         m_isBlocked = true;
1101         Mlt::Service clipService(clip->get_service());
1102
1103 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1104
1105         int ct = 0;
1106         Mlt::Filter *filter = clipService.filter(ct);
1107         while (filter) {
1108             if (index == "-1" || filter->get("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
1109                 clipService.detach(*filter);
1110                 kDebug() << " / / / DLEETED EFFECT: " << ct;
1111             } else ct++;
1112             filter = clipService.filter(ct);
1113         }
1114         m_isBlocked = false;
1115         if (doRefresh) refresh();
1116         delete trackPlaylist;
1117     }
1118 }
1119
1120
1121 void Render::mltAddEffect(int track, GenTime position, QMap <QString, QString> args, bool doRefresh) {
1122
1123     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1124     if (trackPlaylist) {
1125         Mlt::Producer *clip = trackPlaylist->get_clip_at((int)position.frames(m_fps));
1126
1127         if (!clip) {
1128             kDebug() << "**********  CANNOT FIND CLIP TO APPLY EFFECT-----------";
1129             return;
1130         }
1131         Mlt::Service clipService(clip->get_service());
1132         m_isBlocked = true;
1133         // create filter
1134         QString tag = args.value("tag");
1135         //kDebug()<<" / / INSERTING EFFECT: "<<id;
1136         if (tag.startsWith("ladspa")) tag = "ladspa";
1137         char *filterId = decodedString(tag);
1138         Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterId);
1139         if (filter && filter->is_valid())
1140             filter->set("kdenlive_id", filterId);
1141         else {
1142             kDebug() << "filter is NULL";
1143             return;
1144         }
1145
1146         QMap<QString, QString>::Iterator it;
1147         QString keyFrameNumber = "#0";
1148
1149         for (it = args.begin(); it != args.end(); ++it) {
1150             //kDebug()<<" / / INSERTING EFFECT ARGS: "<<it.key()<<": "<<it.data();
1151             QString key;
1152             QString currentKeyFrameNumber;
1153             if (it.key().startsWith("#")) {
1154                 currentKeyFrameNumber = it.key().section(":", 0, 0);
1155                 if (currentKeyFrameNumber != keyFrameNumber) {
1156                     // attach filter to the clip
1157                     clipService.attach(*filter);
1158                     filter = new Mlt::Filter(*m_mltProfile, filterId);
1159                     filter->set("kdenlive_id", filterId);
1160                     keyFrameNumber = currentKeyFrameNumber;
1161                 }
1162                 key = it.key().section(":", 1);
1163             } else key = it.key();
1164             char *name = decodedString(key);
1165             char *value = decodedString(it.value());
1166             filter->set(name, value);
1167             delete[] name;
1168             delete[] value;
1169         }
1170         // attach filter to the clip
1171         clipService.attach(*filter);
1172         delete[] filterId;
1173         m_isBlocked = false;
1174         if (doRefresh) refresh();
1175         delete trackPlaylist;
1176     }
1177
1178 }
1179
1180 void Render::mltEditEffect(int track, GenTime position, QMap <QString, QString> args) {
1181     QString index = args.value("kdenlive_ix");
1182     QString tag =  args.value("tag");
1183     QMap<QString, QString>::Iterator it = args.begin();
1184     if (it.key().startsWith("#") || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
1185         // This is a keyframe effect, to edit it, we remove it and re-add it.
1186         mltRemoveEffect(track, position, index);
1187         mltAddEffect(track, position, args);
1188         return;
1189     }
1190     m_isBlocked = true;
1191     // create filter
1192
1193     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1194     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1195     if (trackPlaylist) {
1196         Mlt::Producer *clip = trackPlaylist->get_clip_at((int)position.frames(m_fps));
1197         if (!clip) {
1198             kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1199             m_isBlocked = false;
1200             return;
1201         }
1202
1203         Mlt::Service clipService(clip->get_service());
1204
1205 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1206
1207         int ct = 0;
1208         Mlt::Filter *filter = clipService.filter(ct);
1209         while (filter) {
1210             if (filter->get("kdenlive_ix") == index) {
1211                 break;
1212             }
1213             ct++;
1214             filter = clipService.filter(ct);
1215         }
1216
1217
1218         if (!filter) {
1219             kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT!!!!!";
1220             mltAddEffect(track, position, args);
1221             m_isBlocked = false;
1222             return;
1223         }
1224
1225         for (it = args.begin(); it != args.end(); ++it) {
1226             kDebug() << " / / EDITING EFFECT ARGS: " << it.key() << ": " << it.value();
1227             char *name = decodedString(it.key());
1228             char *value = decodedString(it.value());
1229             filter->set(name, value);
1230             delete[] name;
1231             delete[] value;
1232         }
1233         m_isBlocked = false;
1234         refresh();
1235         delete trackPlaylist;
1236     }
1237 }
1238
1239 void Render::mltResizeClipEnd(int track, GenTime pos, GenTime in, GenTime out) {
1240     m_isBlocked = true;
1241
1242     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1243     if (trackPlaylist) {
1244         //Mlt::Tractor *tractor = getTractor();
1245         if (trackPlaylist->is_blank_at((int)pos.frames(m_fps) + 1))
1246             kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1247         int clipIndex = trackPlaylist->get_clip_index_at((int)pos.frames(m_fps) + 1);
1248
1249         int previousDuration = trackPlaylist->clip_length(clipIndex) - 1;
1250         int newDuration = (int)(out.frames(m_fps) - 1);
1251
1252         kDebug() << " ** RESIZING CLIP END:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", in: " << in.frames(25) << ", out: " << out.frames(25) << ", PREVIOUS duration: " << previousDuration;
1253         trackPlaylist->resize_clip(clipIndex, (int)in.frames(m_fps), newDuration);
1254         trackPlaylist->consolidate_blanks(0);
1255         if (previousDuration < newDuration) {
1256             // clip was made longer, trim next blank if there is one.
1257             if (trackPlaylist->is_blank(clipIndex + 1)) {
1258                 trackPlaylist->split(clipIndex + 1, newDuration - previousDuration);
1259                 trackPlaylist->remove(clipIndex + 1);
1260             }
1261         } else trackPlaylist->insert_blank(clipIndex + 1, previousDuration - newDuration - 1);
1262
1263         trackPlaylist->consolidate_blanks(0);
1264         //tractor->multitrack()->refresh();
1265         //tractor->refresh();
1266         if (track != 0) mltCheckLength();
1267         //if (tractor)
1268         //    delete tractor;
1269         m_isBlocked = false;
1270         delete trackPlaylist;
1271     }
1272 }
1273
1274 void Render::mltChangeTrackState(int track, bool mute, bool blind) {
1275
1276     Mlt::Tractor *tractor = getTractor();
1277     if (tractor) {
1278         Mlt::Producer trackProducer(tractor->track(track));
1279         if (mute) {
1280             if (blind) trackProducer.set("hide", 3);
1281             else trackProducer.set("hide", 2);
1282         } else if (blind) {
1283             trackProducer.set("hide", 1);
1284         } else {
1285             trackProducer.set("hide", 0);
1286         }
1287         //tractor->multitrack()->refresh();
1288         //tractor->refresh();
1289         //delete tractor;
1290         refresh();
1291         delete tractor;
1292
1293     }
1294 }
1295
1296 void Render::mltResizeClipStart(int track, GenTime pos, GenTime moveEnd, GenTime moveStart, GenTime in, GenTime out) {
1297     m_isBlocked = true;
1298
1299     int moveFrame = (int)((moveEnd - moveStart).frames(m_fps));
1300
1301     Mlt::Playlist *trackPlaylist = getPlaylist(track);
1302     if (trackPlaylist) {
1303         if (trackPlaylist->is_blank_at((int)pos.frames(m_fps) - 1))
1304             kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1305         int clipIndex = trackPlaylist->get_clip_index_at((int)pos.frames(m_fps) - 1);
1306         kDebug() << " ** RESIZING CLIP START:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", moving: " << moveFrame << ", in: " << in.frames(25) << ", out: " << out.frames(25);
1307
1308         trackPlaylist->resize_clip(clipIndex, (int) in.frames(m_fps), (int)out.frames(m_fps));
1309         if (moveFrame > 0) trackPlaylist->insert_blank(clipIndex, moveFrame - 1);
1310         else {
1311             int midpos = (int)moveStart.frames(m_fps) - 1; //+ (moveFrame / 2)
1312             int blankIndex = trackPlaylist->get_clip_index_at(midpos);
1313             int blankLength = trackPlaylist->clip_length(blankIndex);
1314
1315             kDebug() << " + resizing blank: " << blankIndex << ", Mid: " << midpos << ", Length: " << blankLength << ", SIZE DIFF: " << moveFrame;
1316
1317
1318             if (blankLength + moveFrame == 0) trackPlaylist->remove(blankIndex);
1319             else trackPlaylist->resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
1320         }
1321         trackPlaylist->consolidate_blanks(0);
1322         m_isBlocked = false;
1323         kDebug() << "-----------------\n" << "CLIP 0: " << trackPlaylist->clip_start(0) << ", LENGT: " << trackPlaylist->clip_length(0);
1324         kDebug() << "CLIP 1: " << trackPlaylist->clip_start(1) << ", LENGT: " << trackPlaylist->clip_length(1);
1325         kDebug() << "CLIP 2: " << trackPlaylist->clip_start(2) << ", LENGT: " << trackPlaylist->clip_length(2);
1326         kDebug() << "CLIP 3: " << trackPlaylist->clip_start(3) << ", LENGT: " << trackPlaylist->clip_length(3);
1327         kDebug() << "CLIP 4: " << trackPlaylist->clip_start(4) << ", LENGT: " << trackPlaylist->clip_length(4);
1328
1329         delete trackPlaylist;
1330     }
1331 }
1332
1333 void Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd) {
1334     mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps));
1335 }
1336
1337
1338 void Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd) {
1339     m_isBlocked = true;
1340     //m_mltConsumer->set("refresh", 0);
1341     Mlt::Tractor *tractor = getTractor();
1342     if (tractor) {
1343         Mlt::Producer trackProducer(tractor->track(startTrack));
1344         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1345         int clipIndex = trackPlaylist.get_clip_index_at(moveStart + 1);
1346         mlt_field field = mlt_tractor_field(tractor->get_tractor());
1347         mlt_multitrack multitrack = mlt_field_multitrack(field); //mlt_tractor_multitrack(tractor.get_tractor());
1348         kDebug() << " --  CURRENT MULTIOTRACK HAS: " << mlt_multitrack_count(multitrack) << " tracks";;
1349         mlt_service multiprod = mlt_multitrack_service(multitrack);
1350
1351         Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
1352         trackPlaylist.consolidate_blanks(1);
1353         mlt_events_block(MLT_PRODUCER_PROPERTIES(trackProducer.get_producer()), NULL);
1354
1355         if (endTrack == startTrack) {
1356             if (!trackPlaylist.is_blank_at(moveEnd)) {
1357                 kWarning() << "// ERROR, CLIP COLLISION----------";
1358                 int ix = trackPlaylist.get_clip_index_at(moveEnd);
1359                 kDebug() << "BAD CLIP STARTS AT: " << trackPlaylist.clip_start(ix) << ", LENGT: " << trackPlaylist.clip_length(ix);
1360             }
1361             trackPlaylist.insert_at(moveEnd, clipProducer, 1);
1362             trackPlaylist.consolidate_blanks(0);
1363         } else {
1364             trackPlaylist.consolidate_blanks(0);
1365             Mlt::Producer destTrackProducer(tractor->track(endTrack));
1366             Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
1367             destTrackPlaylist.consolidate_blanks(1);
1368             destTrackPlaylist.insert_at(moveEnd, clipProducer, 1);
1369             destTrackPlaylist.consolidate_blanks(0);
1370         }
1371
1372         mltCheckLength();
1373         mlt_events_unblock(MLT_PRODUCER_PROPERTIES(trackProducer.get_producer()), NULL);
1374         m_isBlocked = false;
1375         m_mltConsumer->set("refresh", 1);
1376         delete tractor;
1377     }
1378 }
1379
1380 void Render::mltMoveTransition(QString type, int startTrack, int trackOffset, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut) {
1381     m_isBlocked = true;
1382     m_mltConsumer->set("refresh", 0);
1383
1384     Mlt::Tractor *tractor = getTractor();
1385     if (tractor) {
1386         Mlt::Tractor newTractor;
1387         mlt_service service = tractor->get_service();
1388         mlt_service nextservice = mlt_service_get_producer(service);
1389         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1390         QString mlt_type = mlt_properties_get(properties, "mlt_type");
1391         QString resource = mlt_properties_get(properties, "mlt_service");
1392         int old_pos = (int)(oldIn.frames(m_fps) + oldOut.frames(m_fps)) / 2;
1393
1394         int new_in = (int)newIn.frames(m_fps);
1395         int new_out = (int)newOut.frames(m_fps) - 1;
1396         while (mlt_type == "transition") {
1397             mlt_transition tr = (mlt_transition) nextservice;
1398             int currentTrack = mlt_transition_get_b_track(tr);
1399             int currentIn = (int) mlt_transition_get_in(tr);
1400             int currentOut = (int) mlt_transition_get_out(tr);
1401
1402             //kDebug() << "// OLD IN: " << oldIn.frames(m_fps) << " // OLD OUT: " << oldOut.frames(m_fps) << ", TRACK: " << startTrack << ", CURR TRANS: " <<currentIn<<", MID:"<< old_pos<<currentOut;
1403             if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
1404                 //kDebug() << "// FOUND EXISTING TRANS, IN: " << type << resource << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
1405                 mlt_transition_set_in_and_out(tr, new_in, new_out);
1406                 if (trackOffset != 0) {
1407                     mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
1408                     mlt_properties_set_int(properties, "a_track", mlt_transition_get_a_track(tr) + trackOffset);
1409                     mlt_properties_set_int(properties, "b_track", mlt_transition_get_b_track(tr) + trackOffset);
1410                     //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);
1411                 }
1412                 break;
1413             }
1414             nextservice = mlt_service_producer(nextservice);
1415             properties = MLT_SERVICE_PROPERTIES(nextservice);
1416             mlt_type = mlt_properties_get(properties, "mlt_type");
1417             resource = mlt_properties_get(properties, "mlt_service");
1418         }
1419         m_isBlocked = false;
1420         delete tractor;
1421     }
1422     mltSavePlaylist();
1423     m_mltConsumer->set("refresh", 1);
1424 }
1425
1426 void Render::mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
1427     //kDebug() << "update transition"  << tag;
1428     if (oldTag == tag) mltUpdateTransitionParams(tag, a_track, b_track, in, out, xml);
1429     else {
1430         mltDeleteTransition(oldTag, a_track, b_track, in, out, xml, false);
1431         mltAddTransition(tag, a_track, b_track, in, out, xml);
1432     }
1433     mltSavePlaylist();
1434 }
1435
1436 void Render::mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) {
1437     m_isBlocked = true;
1438     m_mltConsumer->set("refresh", 0);
1439
1440     Mlt::Tractor *tractor = getTractor();
1441     if (tractor) {
1442         Mlt::Tractor newTractor;
1443         mlt_service service = tractor->get_service();
1444         mlt_service nextservice = mlt_service_get_producer(service);
1445         mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1446         QString mlt_type = mlt_properties_get(properties, "mlt_type");
1447         QString resource = mlt_properties_get(properties, "mlt_service");
1448         int in_pos = (int) in.frames(m_fps);
1449         int out_pos = (int) out.frames(m_fps);
1450
1451         while (mlt_type == "transition") {
1452             mlt_transition tr = (mlt_transition) nextservice;
1453             int currentTrack = mlt_transition_get_b_track(tr);
1454             int currentIn = (int) mlt_transition_get_in(tr);
1455             int currentOut = (int) mlt_transition_get_out(tr);
1456             kDebug() << "TRACK: " << b_track << " / " << currentTrack << ", CURR TRANS: " << currentIn << "x" << currentOut << ", LOOKING OFR: " << in_pos << "x" << out_pos;
1457             if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) {
1458                 QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
1459                 QMap<QString, QString>::Iterator it;
1460                 QString key;
1461                 mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr);
1462
1463                 for (it = map.begin(); it != map.end(); ++it) {
1464                     key = it.key();
1465                     char *name = decodedString(key);
1466                     char *value = decodedString(it.value());
1467                     mlt_properties_set(transproperties, name, value);
1468                     kDebug() << " ------  UPDATING TRANS PARAM: " << name << ": " << value;
1469                     //filter->set("kdenlive_id", id);
1470                     delete[] name;
1471                     delete[] value;
1472                 }
1473                 break;
1474             }
1475             nextservice = mlt_service_producer(nextservice);
1476             properties = MLT_SERVICE_PROPERTIES(nextservice);
1477             mlt_type = mlt_properties_get(properties, "mlt_type");
1478             resource = mlt_properties_get(properties, "mlt_service");
1479         }
1480         m_isBlocked = false;
1481         delete tractor;
1482     }
1483     m_mltConsumer->set("refresh", 1);
1484 }
1485
1486 void Render::replaceTimelineTractor(Mlt::Tractor t) {
1487     Mlt::Service service(m_mltProducer->get_service());
1488     Mlt::Playlist prod(service);
1489     Mlt::Service service_playlist(prod.get_clip(0)->get_service());
1490     prod.remove(0);
1491     prod.insert(t, 0);
1492     kDebug() << "newTractor inserted";
1493 }
1494
1495 void Render::mltDeleteTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
1496
1497     Mlt::Tractor *tractor = getTractor();
1498     if (tractor) {
1499         Mlt::Tractor newTractor;
1500         mlt_service service = tractor->get_service();
1501         mlt_service nextservice = mlt_service_get_producer(service);
1502         int old_position = m_mltProducer->position();
1503         for (int track = 0;track < 10;track++) {
1504             Mlt::Producer *trackprod = tractor->track(track);
1505             if (!trackprod)
1506                 continue;
1507             newTractor.multitrack()->connect(*trackprod, track);
1508         }
1509         for (int i = 2;i <= 5;i++) {
1510             Mlt::Transition tr(*m_mltProfile, "mix");
1511             tr.set("combine", 1);
1512             tr.set("internal_added", 237);
1513             tr.set_in_and_out(0, 15000);
1514             newTractor.plant_transition(tr, 1, i);
1515         }
1516         while (nextservice != NULL) {
1517             mlt_properties prop = MLT_SERVICE_PROPERTIES(nextservice);
1518             //kDebug() << mlt_properties_get(prop, "mlt_type") << mlt_properties_get(prop, "id");
1519             if (QString(mlt_properties_get(prop, "mlt_type")) == "transition" && QString(mlt_properties_get(prop, "internal_added")) != "237") {
1520
1521                 mlt_transition tr = (mlt_transition) nextservice;
1522                 Mlt::Transition transition(tr);
1523                 int current_a_track = mlt_transition_get_a_track(tr);
1524                 int current_b_track = mlt_transition_get_b_track(tr);
1525                 int currentIn = (int) mlt_transition_get_in(tr);
1526                 int currentOut = (int) mlt_transition_get_out(tr);
1527                 int old_pos = (int)((in.frames(m_fps) + out.frames(m_fps)) / 2);
1528                 kDebug() << current_a_track << current_b_track << a_track << b_track << currentIn << currentOut << old_pos << mlt_properties_get(prop, "mlt_service");
1529                 if (current_a_track == a_track &&  b_track == current_b_track && currentIn <= old_pos && currentOut >= old_pos) {
1530                     kDebug() << "removing " << mlt_properties_get(prop, "mlt_service");
1531                 } else
1532                     newTractor.plant_transition(transition, current_a_track, current_b_track);
1533             }
1534             nextservice = mlt_service_producer(nextservice);
1535         }
1536
1537         replaceTimelineTractor(newTractor);
1538         m_mltProducer->seek(old_position);
1539         delete tractor;
1540         if (do_refresh) refresh();
1541     }
1542
1543 }
1544
1545 QMap<QString, QString> Render::mltGetTransitionParamsFromXml(QDomElement xml) {
1546     QDomNodeList attribs = xml.elementsByTagName("parameter");
1547     QMap<QString, QString> map;
1548     for (int i = 0;i < attribs.count();i++) {
1549         QDomElement e = attribs.item(i).toElement();
1550         QString name = e.attribute("name");
1551         //kDebug()<<"-- TRANSITION PARAM: "<<name<<" = "<< e.attribute("name")<<" / " << e.attribute("value");
1552         map[name] = e.attribute("default");
1553         if (!e.attribute("value").isEmpty()) {
1554             map[name] = e.attribute("value");
1555         }
1556         if (!e.attribute("factor").isEmpty() && e.attribute("factor").toDouble() > 0) {
1557             map[name] = QString::number(map[name].toDouble() / e.attribute("factor").toDouble());
1558             //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
1559         }
1560
1561         if (e.attribute("namedesc").contains(";")) {
1562             QString format = e.attribute("format");
1563             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1564             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1565             QString neu;
1566             QTextStream txtNeu(&neu);
1567             if (values.size() > 0)
1568                 txtNeu << (int)values[0].toDouble();
1569             int i = 0;
1570             for (i = 0;i < separators.size() && i + 1 < values.size();i++) {
1571                 txtNeu << separators[i];
1572                 txtNeu << (int)(values[i+1].toDouble());
1573             }
1574             if (i < separators.size())
1575                 txtNeu << separators[i];
1576             map[e.attribute("name")] = neu;
1577         }
1578
1579     }
1580     return map;
1581 }
1582
1583 void Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool do_refresh) {
1584     //kDebug() << "-- ADDING TRANSITION: " << tag << ", ON TRACKS: " << a_track << ", " << b_track;
1585     QMap<QString, QString> map = mltGetTransitionParamsFromXml(xml);
1586
1587     Mlt::Tractor *tractor = getTractor();
1588     if (tractor) {
1589         Mlt::Field *field = tractor->field();
1590         char *transId = decodedString(tag);
1591         Mlt::Transition transition(*m_mltProfile, transId);
1592         if (!transition.get_transition()) {
1593             kDebug() << "NO transition is " << transition.get_transition() << "requested was " << tag << a_track << b_track << in.frames(m_fps) << out.frames(m_fps);
1594             return;
1595         }
1596         transition.set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps));
1597         QMap<QString, QString>::Iterator it;
1598         QString key;
1599
1600         kDebug() << " ------  ADDING TRANSITION PARAMs: " << map.count();
1601
1602         for (it = map.begin(); it != map.end(); ++it) {
1603             key = it.key();
1604             char *name = decodedString(key);
1605             char *value = decodedString(it.value());
1606             transition.set(name, value);
1607             kDebug() << " ------  ADDING TRANS PARAM: " << name << ": " << value;
1608             //filter->set("kdenlive_id", id);
1609             delete[] name;
1610             delete[] value;
1611         }
1612         // attach filter to the clip
1613         field->plant_transition(transition, a_track, b_track);
1614         delete[] transId;
1615         mltSavePlaylist();
1616         if (do_refresh) refresh();
1617         delete tractor;
1618     }
1619 }
1620
1621 void Render::mltSavePlaylist() {
1622     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
1623     Mlt::Consumer fileConsumer(*m_mltProfile, "westley");
1624     fileConsumer.set("resource", "/tmp/playlist.westley");
1625
1626     Mlt::Service service(m_mltProducer->get_service());
1627
1628     fileConsumer.connect(service);
1629     fileConsumer.start();
1630
1631 }
1632
1633 #include "renderer.moc"
1634