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