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