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