]> git.sesse.net Git - kdenlive/blob - src/renderer.cpp
Looks like I finally got the profile switching work!
[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
44 static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr) {
45     // detect if the producer has finished playing. Is there a better way to do it ?
46     //if (self->isBlocked) return;
47     if (mlt_properties_get_double(MLT_FRAME_PROPERTIES(frame_ptr), "_speed") == 0.0) {
48         self->emitConsumerStopped();
49     } else {
50         self->emitFrameNumber(mlt_frame_get_position(frame_ptr));
51     }
52 }
53
54 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) {
55     kDebug() << "//////////  USING PROFILE: " << (char *)KdenliveSettings::current_profile().toUtf8().data();
56     m_mltProfile = new Mlt::Profile((char*) KdenliveSettings::current_profile().data());
57     refreshTimer = new QTimer(this);
58     connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
59
60     m_connectTimer = new QTimer(this);
61     connect(m_connectTimer, SIGNAL(timeout()), this, SLOT(connectPlaylist()));
62
63     if (rendererName == "project") m_monitorId = 10000;
64     else m_monitorId = 10001;
65     osdTimer = new QTimer(this);
66     connect(osdTimer, SIGNAL(timeout()), this, SLOT(slotOsdTimeout()));
67
68     m_osdProfile =   KStandardDirs::locate("data", "kdenlive/profiles/metadata.properties");
69     //if (rendererName == "clip")
70     {
71         //Mlt::Consumer *consumer = new Mlt::Consumer( profile , "sdl_preview");
72         m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview"); //consumer;
73         m_mltConsumer->set("resize", 1);
74         m_mltConsumer->set("window_id", winid);
75         m_mltConsumer->set("terminate_on_pause", 1);
76         m_externalwinid = extid;
77         m_winid = winid;
78         m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
79         Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "westley-xml", "<westley><playlist><producer mlt_service=\"colour\" colour=\"blue\" in=\"0\" out=\"25\" /></playlist></westley>");
80         m_mltProducer = producer;
81         m_mltConsumer->connect(*m_mltProducer);
82         m_mltProducer->set_speed(0.0);
83         //m_mltConsumer->start();
84         //refresh();
85         //initSceneList();
86     }
87     /*m_osdInfo = new Mlt::Filter("data_show");
88     char *tmp = decodedString(m_osdProfile);
89     m_osdInfo->set("resource", tmp);
90     delete[] tmp;*/
91     //      Does it do anything usefull? I mean, RenderThread doesn't do anything useful at the moment
92     //      (except being cpu hungry :)
93
94     /*      if(!s_renderThread) {
95     s_renderThread = new RenderThread;
96     s_renderThread->start();
97     } */
98 }
99
100 Render::~Render() {
101     closeMlt();
102 }
103
104
105 void Render::closeMlt() {
106     delete m_connectTimer;
107     delete osdTimer;
108     delete refreshTimer;
109     if (m_mltConsumer)
110         delete m_mltConsumer;
111     if (m_mltProducer)
112         delete m_mltProducer;
113     //delete m_osdInfo;
114 }
115
116
117
118 int Render::resetProfile(QString profile) {
119     if (!m_mltConsumer) return 0;
120     if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
121     m_mltConsumer->set("refresh", 0);
122     m_mltConsumer->purge();
123     delete m_mltConsumer;
124     m_mltConsumer = NULL;
125     QString scene = sceneList();
126     if (m_mltProducer) delete m_mltProducer;
127     m_mltProducer = NULL;
128     if (m_mltProfile) delete m_mltProfile;
129     m_mltProfile = NULL;
130
131     m_mltProfile = new Mlt::Profile((char*) profile.toUtf8().data());
132     m_mltConsumer = new Mlt::Consumer(*m_mltProfile , "sdl_preview"); //consumer;
133     m_mltConsumer->set("resize", 1);
134     m_mltConsumer->set("window_id", m_winid);
135     m_mltConsumer->set("terminate_on_pause", 1);
136     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_frame_show);
137
138     Mlt::Producer *producer = new Mlt::Producer(*m_mltProfile , "westley-xml", (char *) scene.toUtf8().data());
139     m_mltProducer = producer;
140     m_mltConsumer->connect(*m_mltProducer);
141     m_mltProducer->set_speed(0.0);
142
143     //delete m_mltProfile;
144     // mlt_properties properties = MLT_CONSUMER_PROPERTIES(m_mltConsumer->get_consumer());
145     //mlt_profile prof = m_mltProfile->get_profile();
146     //mlt_properties_set_data(properties, "_profile", prof, 0, (mlt_destructor)mlt_profile_close, NULL);
147     //mlt_properties_set(properties, "profile", "hdv_1080_50i");
148     //m_mltConsumer->set("profile", (char *) profile.toUtf8().data());
149     //m_mltProfile = new Mlt::Profile((char*) profile.toUtf8().data());
150     kDebug() << " ++++++++++ RESET CONSUMER WITH PROFILE: " << profile << ", WIDTH: " << m_mltProfile->width();
151
152     //apply_profile_properties( m_mltProfile, m_mltConsumer->get_consumer(), properties );
153     //refresh();
154     return 1;
155 }
156
157 /** Wraps the VEML command of the same name; Seeks the renderer clip to the given time. */
158 void Render::seek(GenTime time) {
159     sendSeekCommand(time);
160     //emit positionChanged(time);
161 }
162
163 //static
164 char *Render::decodedString(QString str) {
165     /*QCString fn = QFile::encodeName(str);
166     char *t = new char[fn.length() + 1];
167     strcpy(t, (const char *)fn);*/
168
169     return (char *) qstrdup(str.toUtf8().data());   //toLatin1
170 }
171
172 //static
173 QPixmap Render::frameThumbnail(Mlt::Frame *frame, int width, int height, bool border) {
174     QPixmap pix(width, height);
175
176     mlt_image_format format = mlt_image_rgb24a;
177     uint8_t *thumb = frame->get_image(format, width, height);
178     QImage image(thumb, width, height, QImage::Format_ARGB32);
179
180     if (!image.isNull()) {
181         pix = pix.fromImage(image);
182         if (border) {
183             QPainter painter(&pix);
184             painter.drawRect(0, 0, width - 1, height - 1);
185         }
186     } else pix.fill(Qt::black);
187     return pix;
188 }
189
190
191 QPixmap Render::extractFrame(int frame_position, int width, int height) {
192     QPixmap pix(width, height);
193     if (!m_mltProducer) {
194         pix.fill(Qt::black);
195         return pix;
196     }
197     Mlt::Producer *mlt_producer = m_mltProducer->cut(frame_position, frame_position + 1);
198     Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
199     m_convert.set("forced", mlt_image_rgb24a);
200     mlt_producer->attach(m_convert);
201     Mlt::Frame *frame = mlt_producer->get_frame();
202
203     if (frame) {
204         pix = frameThumbnail(frame, width, height);
205         delete frame;
206     } else pix.fill(Qt::black);
207     delete mlt_producer;
208     return pix;
209 }
210
211 QPixmap Render::getImageThumbnail(KUrl url, int width, int height) {
212     QImage im;
213     QPixmap pixmap;
214     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
215         QString fileType = url.fileName().right(3);
216         QStringList more;
217         QStringList::Iterator it;
218
219         QDir dir(url.directory());
220         more = dir.entryList(QDir::Files);
221
222         for (it = more.begin() ; it != more.end() ; ++it) {
223             if ((*it).endsWith("." + fileType, Qt::CaseInsensitive)) {
224                 im.load(url.directory() + "/" + *it);
225                 break;
226             }
227         }
228     } else im.load(url.path());
229     //pixmap = im.scaled(width, height);
230     return pixmap;
231 }
232
233 //static
234 QPixmap Render::getVideoThumbnail(char *profile, QString file, int frame_position, int width, int height) {
235     QPixmap pix(width, height);
236     char *tmp = decodedString(file);
237     Mlt::Profile *prof = new Mlt::Profile(profile);
238     Mlt::Producer m_producer(*prof, tmp);
239     delete[] tmp;
240     if (m_producer.is_blank()) {
241         pix.fill(Qt::black);
242         return pix;
243     }
244
245     Mlt::Filter m_convert(*prof, "avcolour_space");
246     m_convert.set("forced", mlt_image_rgb24a);
247     m_producer.attach(m_convert);
248     m_producer.seek(frame_position);
249     Mlt::Frame * frame = m_producer.get_frame();
250     if (frame) {
251         pix = frameThumbnail(frame, width, height, true);
252         delete frame;
253     }
254     if (prof) delete prof;
255     return pix;
256 }
257
258 /*
259 void Render::getImage(KUrl url, int frame_position, QPoint size)
260 {
261     char *tmp = decodedString(url.path());
262     Mlt::Producer m_producer(tmp);
263     delete[] tmp;
264     if (m_producer.is_blank()) {
265  return;
266     }
267     Mlt::Filter m_convert("avcolour_space");
268     m_convert.set("forced", mlt_image_rgb24a);
269     m_producer.attach(m_convert);
270     m_producer.seek(frame_position);
271
272     Mlt::Frame * frame = m_producer.get_frame();
273
274     if (frame) {
275  QPixmap pix = frameThumbnail(frame, size.x(), size.y(), true);
276  delete frame;
277  emit replyGetImage(url, frame_position, pix, size.x(), size.y());
278     }
279 }*/
280
281 /* Create thumbnail for color */
282 /*void Render::getImage(int id, QString color, QPoint size)
283 {
284     QPixmap pixmap(size.x() - 2, size.y() - 2);
285     color = color.replace(0, 2, "#");
286     color = color.left(7);
287     pixmap.fill(QColor(color));
288     QPixmap result(size.x(), size.y());
289     result.fill(Qt::black);
290     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
291     emit replyGetImage(id, result, size.x(), size.y());
292
293 }*/
294
295 /* Create thumbnail for image */
296 /*void Render::getImage(KUrl url, QPoint size)
297 {
298     QImage im;
299     QPixmap pixmap;
300     if (url.fileName().startsWith(".all.")) {  //  check for slideshow
301      QString fileType = url.fileName().right(3);
302          QStringList more;
303          QStringList::Iterator it;
304
305             QDir dir( url.directory() );
306             more = dir.entryList( QDir::Files );
307             for ( it = more.begin() ; it != more.end() ; ++it ) {
308                 if ((*it).endsWith("."+fileType, Qt::CaseInsensitive)) {
309    if (!im.load(url.directory() + "/" + *it))
310        kDebug()<<"++ ERROR LOADIN IMAGE: "<<url.directory() + "/" + *it;
311    break;
312   }
313      }
314     }
315     else im.load(url.path());
316
317     //pixmap = im.smoothScale(size.x() - 2, size.y() - 2);
318     QPixmap result(size.x(), size.y());
319     result.fill(Qt::black);
320     //copyBlt(&result, 1, 1, &pixmap, 0, 0, size.x() - 2, size.y() - 2);
321     emit replyGetImage(url, 1, result, size.x(), size.y());
322 }*/
323
324
325 double Render::consumerRatio() const {
326     if (!m_mltConsumer) return 1.0;
327     return (m_mltConsumer->get_double("aspect_ratio_num") / m_mltConsumer->get_double("aspect_ratio_den"));
328 }
329
330
331 int Render::getLength() {
332
333     if (m_mltProducer) {
334         // kDebug()<<"//////  LENGTH: "<<mlt_producer_get_playtime(m_mltProducer->get_producer());
335         return mlt_producer_get_playtime(m_mltProducer->get_producer());
336     }
337     return 0;
338 }
339
340 bool Render::isValid(KUrl url) {
341     char *tmp = decodedString(url.path());
342     Mlt::Producer producer(*m_mltProfile, tmp);
343     delete[] tmp;
344     if (producer.is_blank())
345         return false;
346
347     return true;
348 }
349
350 void Render::getFileProperties(const QDomElement &xml, int clipId) {
351     int height = 40;
352     int width = height * 16 / 9.0; //KdenliveSettings::displayratio();
353     QDomDocument doc;
354     QDomElement westley = doc.createElement("westley");
355     doc.appendChild(westley);
356     westley.appendChild(doc.importNode(xml, true));
357     kDebug() << "////////////\n" << doc.toString() << "////////////////\n";
358     char *tmp = decodedString(doc.toString());
359
360     Mlt::Producer producer(*m_mltProfile, "westley-xml", tmp);
361     delete[] tmp;
362
363     if (producer.is_blank()) {
364         return;
365     }
366     int frameNumber = xml.attribute("frame_thumbnail", 0).toInt();
367     if (frameNumber != 0) producer.seek(frameNumber);
368     mlt_properties properties = MLT_PRODUCER_PROPERTIES(producer.get_producer());
369
370     QMap < QString, QString > filePropertyMap;
371     QMap < QString, QString > metadataPropertyMap;
372
373     KUrl url = xml.attribute("resource", QString::null);
374     filePropertyMap["filename"] = url.path();
375     filePropertyMap["duration"] = QString::number(producer.get_playtime());
376     kDebug() << "///////  PRODUCER: " << url.path() << " IS: " << producer.get_playtime();
377     Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
378     m_convert.set("forced", mlt_image_rgb24a);
379     producer.attach(m_convert);
380     Mlt::Frame * frame = producer.get_frame();
381
382     filePropertyMap["fps"] =
383         QString::number(mlt_producer_get_fps(producer.get_producer()));
384
385     if (frame && frame->is_valid()) {
386         filePropertyMap["width"] =
387             QString::number(frame->get_int("width"));
388         filePropertyMap["height"] =
389             QString::number(frame->get_int("height"));
390         filePropertyMap["frequency"] =
391             QString::number(frame->get_int("frequency"));
392         filePropertyMap["channels"] =
393             QString::number(frame->get_int("channels"));
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 = frameThumbnail(frame, width, height, true);
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 0 //until the reason for the chrashs is found
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
436
437     // metadata
438
439     mlt_properties metadata = mlt_properties_new();
440     mlt_properties_pass(metadata, properties, "meta.attr.");
441     int count = mlt_properties_count(metadata);
442     for (int i = 0; i < count; i ++) {
443         QString name = mlt_properties_get_name(metadata, i);
444         QString value = QString::fromUtf8(mlt_properties_get_value(metadata, i));
445         if (name.endsWith("markup") && !value.isEmpty())
446             metadataPropertyMap[ name.section(".", 0, -2)] = value;
447     }
448
449     emit replyGetFileProperties(clipId, filePropertyMap, metadataPropertyMap);
450     kDebug() << "REquested fuile info for: " << url.path();
451     if (frame) delete frame;
452 }
453
454 /** Create the producer from the Westley QDomDocument */
455 void Render::initSceneList() {
456     kDebug() << "--------  INIT SCENE LIST ------_";
457     QDomDocument doc;
458     QDomElement westley = doc.createElement("westley");
459     doc.appendChild(westley);
460     QDomElement prod = doc.createElement("producer");
461     prod.setAttribute("resource", "colour");
462     prod.setAttribute("colour", "red");
463     prod.setAttribute("id", "black");
464     prod.setAttribute("in", "0");
465     prod.setAttribute("out", "0");
466
467     QDomElement tractor = doc.createElement("tractor");
468     QDomElement multitrack = doc.createElement("multitrack");
469
470     QDomElement playlist1 = doc.createElement("playlist");
471     playlist1.appendChild(prod);
472     multitrack.appendChild(playlist1);
473     QDomElement playlist2 = doc.createElement("playlist");
474     multitrack.appendChild(playlist2);
475     QDomElement playlist3 = doc.createElement("playlist");
476     multitrack.appendChild(playlist3);
477     QDomElement playlist4 = doc.createElement("playlist");
478     multitrack.appendChild(playlist4);
479     QDomElement playlist5 = doc.createElement("playlist");
480     multitrack.appendChild(playlist5);
481     tractor.appendChild(multitrack);
482     westley.appendChild(tractor);
483     // kDebug()<<doc.toString();
484     /*
485        QString tmp = QString("<westley><producer resource=\"colour\" colour=\"red\" id=\"red\" /><tractor><multitrack><playlist></playlist><playlist></playlist><playlist /><playlist /><playlist></playlist></multitrack></tractor></westley>");*/
486     setSceneList(doc, 0);
487 }
488
489 /** Create the producer from the Westley QDomDocument */
490 void Render::setSceneList(QDomDocument list, int position) {
491     setSceneList(list.toString(), position);
492 }
493
494 /** Create the producer from the Westley QDomDocument */
495 void Render::setSceneList(QString playlist, int position) {
496     if (m_winid == -1) return;
497     m_generateScenelist = true;
498
499     kWarning() << "//////  RENDER, SET SCENE LIST: " << playlist;
500
501
502     /*
503         if (!clip.is_valid()) {
504      kWarning()<<" ++++ WARNING, UNABLE TO CREATE MLT PRODUCER";
505      m_generateScenelist = false;
506      return;
507         }*/
508
509     if (m_mltConsumer) {
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     }
722     kDebug() << "/////////////   RENDER STOP3-------";
723 }
724
725 void Render::stop(const GenTime & startTime) {
726     kDebug() << "/////////////   RENDER STOP-------2";
727     if (m_mltProducer) {
728         m_mltProducer->set_speed(0.0);
729         m_mltProducer->seek((int) startTime.frames(m_fps));
730     }
731     m_mltConsumer->purge();
732 }
733
734 void Render::switchPlay() {
735     if (!m_mltProducer)
736         return;
737     if (m_mltProducer->get_speed() == 0.0) m_mltProducer->set_speed(1.0);
738     else {
739         m_mltProducer->set_speed(0.0);
740         kDebug() << "// POSITON: " << m_framePosition;
741         m_mltProducer->seek((int) m_framePosition);
742     }
743
744     /*if (speed == 0.0) {
745     m_mltProducer->seek((int) m_framePosition + 1);
746         m_mltConsumer->purge();
747     }*/
748     refresh();
749 }
750
751 void Render::play(double speed) {
752     if (!m_mltProducer)
753         return;
754     if (speed == 0.0) m_mltProducer->set("out", m_mltProducer->get_length() - 1);
755     m_mltProducer->set_speed(speed);
756     /*if (speed == 0.0) {
757     m_mltProducer->seek((int) m_framePosition + 1);
758         m_mltConsumer->purge();
759     }*/
760     refresh();
761 }
762
763 void Render::play(double speed, const GenTime & startTime) {
764     kDebug() << "/////////////   RENDER PLAY2-------" << speed;
765     if (!m_mltProducer)
766         return;
767     //m_mltProducer->set("out", m_mltProducer->get_length() - 1);
768     //if (speed == 0.0) m_mltConsumer->set("refresh", 0);
769     m_mltProducer->set_speed(speed);
770     m_mltProducer->seek((int)(startTime.frames(m_fps)));
771     //m_mltConsumer->purge();
772     //refresh();
773 }
774
775 void Render::play(double speed, const GenTime & startTime,
776                   const GenTime & stopTime) {
777     kDebug() << "/////////////   RENDER PLAY3-------" << speed;
778     if (!m_mltProducer)
779         return;
780     m_mltProducer->set("out", stopTime.frames(m_fps));
781     m_mltProducer->seek((int)(startTime.frames(m_fps)));
782     m_mltConsumer->purge();
783     m_mltProducer->set_speed(speed);
784     refresh();
785 }
786
787
788 void Render::sendSeekCommand(GenTime time) {
789     if (!m_mltProducer)
790         return;
791     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
792     m_mltProducer->seek((int)(time.frames(m_fps)));
793     refresh();
794 }
795
796 void Render::seekToFrame(int pos) {
797     if (!m_mltProducer)
798         return;
799     //kDebug()<<"//////////  KDENLIVE SEEK: "<<(int) (time.frames(m_fps));
800     m_mltProducer->seek(pos);
801     refresh();
802 }
803
804 void Render::askForRefresh() {
805     // Use a Timer so that we don't refresh too much
806     refreshTimer->start(200);
807 }
808
809 void Render::doRefresh() {
810     // Use a Timer so that we don't refresh too much
811     refresh();
812 }
813
814 void Render::refresh() {
815     if (!m_mltProducer || m_isBlocked)
816         return;
817     refreshTimer->stop();
818     if (m_mltConsumer) {
819         m_mltConsumer->set("refresh", 1);
820     }
821 }
822
823 /** Sets the description of this renderer to desc. */
824 void Render::setDescription(const QString & description) {
825     m_description = description;
826 }
827
828 /** Returns the description of this renderer */
829 QString Render::description() {
830     return m_description;
831 }
832
833
834 double Render::playSpeed() {
835     if (m_mltProducer) return m_mltProducer->get_speed();
836     return 0.0;
837 }
838
839 const GenTime & Render::seekPosition() const {
840     if (m_mltProducer) return GenTime((int) m_mltProducer->position(), m_fps);
841     else return GenTime();
842 }
843
844
845 const QString & Render::rendererName() const {
846     return m_name;
847 }
848
849
850 void Render::emitFrameNumber(double position) {
851     //kDebug()<<"// POSITON: "<<m_framePosition;
852     if (m_generateScenelist) return;
853     m_framePosition = position;
854     emit rendererPosition((int) position);
855     //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent( GenTime((int) position, m_fps), m_monitorId));
856 }
857
858 void Render::emitConsumerStopped() {
859     // This is used to know when the playing stopped
860     if (m_mltProducer && !m_generateScenelist) {
861         double pos = m_mltProducer->position();
862         emit rendererStopped((int) pos);
863         //if (qApp->activeWindow()) QApplication::postEvent(qApp->activeWindow(), new PositionChangeEvent(GenTime((int) pos, m_fps), m_monitorId + 100));
864         //new QCustomEvent(10002));
865     }
866 }
867
868
869
870 void Render::exportFileToFirewire(QString srcFileName, int port, GenTime startTime, GenTime endTime) {
871     KMessageBox::sorry(0, i18n("Firewire is not enabled on your system.\n Please install Libiec61883 and recompile Kdenlive"));
872 }
873
874
875 void Render::exportCurrentFrame(KUrl url, bool notify) {
876     if (!m_mltProducer) {
877         KMessageBox::sorry(qApp->activeWindow(), i18n("There is no clip, cannot extract frame."));
878         return;
879     }
880
881     int height = 1080;//KdenliveSettings::defaultheight();
882     int width = 1940; //KdenliveSettings::displaywidth();
883
884     QPixmap pix(width, height);
885     Mlt::Filter m_convert(*m_mltProfile, "avcolour_space");
886     m_convert.set("forced", mlt_image_rgb24a);
887     m_mltProducer->attach(m_convert);
888     Mlt::Frame * frame = m_mltProducer->get_frame();
889     m_mltProducer->detach(m_convert);
890     if (frame) {
891         pix = frameThumbnail(frame, width, height);
892         delete frame;
893     }
894     pix.save(url.path(), "PNG");
895     //if (notify) QApplication::postEvent(qApp->activeWindow(), new UrlEvent(url, 10003));
896 }
897
898 /** MLT PLAYLIST DIRECT MANIPULATON  **/
899
900
901 void Render::mltCheckLength() {
902     //kDebug()<<"checking track length: "<<track<<"..........";
903     Mlt::Service service(m_mltProducer->get_service());
904     Mlt::Tractor tractor(service);
905
906     int trackNb = tractor.count();
907     double duration = 0;
908     double trackDuration;
909     if (trackNb == 1) {
910         Mlt::Producer trackProducer(tractor.track(0));
911         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
912         duration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
913         m_mltProducer->set("out", duration);
914         emit durationChanged(duration);
915         return;
916     }
917     while (trackNb > 1) {
918         Mlt::Producer trackProducer(tractor.track(trackNb - 1));
919         Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
920         trackDuration = Mlt::Producer(trackPlaylist.get_producer()).get_playtime() - 1;
921
922         kDebug() << " / / /DURATON FOR TRACK " << trackNb - 1 << " = " << trackDuration;
923         if (trackDuration > duration) duration = trackDuration;
924         trackNb--;
925     }
926
927     Mlt::Producer blackTrackProducer(tractor.track(0));
928     Mlt::Playlist blackTrackPlaylist((mlt_playlist) blackTrackProducer.get_service());
929     double blackDuration = Mlt::Producer(blackTrackPlaylist.get_producer()).get_playtime() - 1;
930     kDebug() << " / / /DURATON FOR TRACK 0 = " << blackDuration;
931     if (blackDuration != duration) {
932         blackTrackPlaylist.remove_region(0, blackDuration);
933         int i = 0;
934         int dur = duration;
935         QDomDocument doc;
936         QDomElement black = doc.createElement("producer");
937         black.setAttribute("mlt_service", "colour");
938         black.setAttribute("colour", "black");
939         black.setAttribute("in", "0");
940         black.setAttribute("out", "13999");
941         while (dur > 14000) { // <producer mlt_service=\"colour\" colour=\"black\" in=\"0\" out=\"13999\" />
942             mltInsertClip(0, GenTime(i * 14000, m_fps), black);
943             dur = dur - 14000;
944             i++;
945         }
946         black.setAttribute("out", QString::number(dur));
947         mltInsertClip(0, GenTime(), black);
948
949         m_mltProducer->set("out", duration);
950         emit durationChanged(duration);
951     }
952 }
953
954
955 void Render::mltInsertClip(int track, GenTime position, QDomElement element) {
956     if (!m_mltProducer) {
957         kDebug() << "PLAYLIST NOT INITIALISED //////";
958         return;
959     }
960     Mlt::Producer parentProd(m_mltProducer->parent());
961     if (parentProd.get_producer() == NULL) {
962         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
963         return;
964     }
965     m_isBlocked = true;
966     Mlt::Service service(parentProd.get_service());
967     Mlt::Tractor tractor(service);
968
969     QDomDocument doc;
970     doc.appendChild(doc.importNode(element, true));
971     QString resource = doc.toString();
972     kDebug() << "///////  ADDING CLIP TMLNE: " << resource << " ON TRACK: " << track;
973     Mlt::Producer trackProducer(tractor.track(track));
974     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
975     char *tmp = decodedString(resource);
976     Mlt::Producer clip(*m_mltProfile, "westley-xml", tmp);
977     //clip.set_in_and_out(in.frames(m_fps), out.frames(m_fps));
978     delete[] tmp;
979
980     trackPlaylist.insert_at(position.frames(m_fps), clip, 1);
981     tractor.multitrack()->refresh();
982     tractor.refresh();
983     if (track != 0) mltCheckLength();
984     m_isBlocked = false;
985 }
986
987 void Render::mltCutClip(int track, GenTime position) {
988     m_isBlocked = true;
989     Mlt::Service service(m_mltProducer->parent().get_service());
990     Mlt::Tractor tractor(service);
991     Mlt::Producer trackProducer(tractor.track(track));
992     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
993     trackPlaylist.split_at(position.frames(m_fps));
994     trackPlaylist.consolidate_blanks(0);
995     kDebug() << "/ / / /CUTTING CLIP AT: " << position.frames(m_fps);
996     m_isBlocked = false;
997 }
998
999
1000 void Render::mltRemoveClip(int track, GenTime position) {
1001     m_isBlocked = true;
1002     Mlt::Service service(m_mltProducer->parent().get_service());
1003     Mlt::Tractor tractor(service);
1004     Mlt::Producer trackProducer(tractor.track(track));
1005     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1006     int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1007     //trackPlaylist.remove(clipIndex);
1008     trackPlaylist.replace_with_blank(clipIndex);
1009     trackPlaylist.consolidate_blanks(0);
1010     if (track != 0) mltCheckLength();
1011     //emit durationChanged();
1012     m_isBlocked = false;
1013 }
1014
1015 void Render::mltRemoveEffect(int track, GenTime position, QString index, bool doRefresh) {
1016
1017     Mlt::Service service(m_mltProducer->parent().get_service());
1018
1019     Mlt::Tractor tractor(service);
1020     Mlt::Producer trackProducer(tractor.track(track));
1021     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1022     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1023     Mlt::Producer *clip = trackPlaylist.get_clip_at(position.frames(m_fps));
1024     if (!clip) {
1025         kDebug() << " / / / CANNOT FIND CLIP TO REMOVE EFFECT";
1026         return;
1027     }
1028     m_isBlocked = true;
1029     Mlt::Service clipService(clip->get_service());
1030
1031 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1032
1033     int ct = 0;
1034     Mlt::Filter *filter = clipService.filter(ct);
1035     while (filter) {
1036         if (index == "-1" || filter->get("kdenlive_ix") == index) {// && filter->get("kdenlive_id") == id) {
1037             clipService.detach(*filter);
1038             kDebug() << " / / / DLEETED EFFECT: " << ct;
1039         } else ct++;
1040         filter = clipService.filter(ct);
1041     }
1042     m_isBlocked = false;
1043     if (doRefresh) refresh();
1044 }
1045
1046
1047 void Render::mltAddEffect(int track, GenTime position, QMap <QString, QString> args, bool doRefresh) {
1048     Mlt::Service service(m_mltProducer->parent().get_service());
1049     Mlt::Tractor tractor(service);
1050     Mlt::Producer trackProducer(tractor.track(track));
1051     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1052
1053     Mlt::Producer *clip = trackPlaylist.get_clip_at(position.frames(m_fps));
1054
1055     if (!clip) {
1056         kDebug() << "**********  CANNOT FIND CLIP TO APPLY EFFECT-----------";
1057         return;
1058     }
1059     Mlt::Service clipService(clip->get_service());
1060     m_isBlocked = true;
1061     // create filter
1062     QString tag = args.value("tag");
1063     //kDebug()<<" / / INSERTING EFFECT: "<<id;
1064     if (tag.startsWith("ladspa")) tag = "ladspa";
1065     char *filterId = decodedString(tag);
1066     Mlt::Filter *filter = new Mlt::Filter(*m_mltProfile, filterId);
1067     if (filter && filter->is_valid())
1068         filter->set("kdenlive_id", filterId);
1069     else {
1070         kDebug() << "filter is NULL";
1071         return;
1072     }
1073
1074     QMap<QString, QString>::Iterator it;
1075     QString keyFrameNumber = "#0";
1076
1077     for (it = args.begin(); it != args.end(); ++it) {
1078         //kDebug()<<" / / INSERTING EFFECT ARGS: "<<it.key()<<": "<<it.data();
1079         QString key;
1080         QString currentKeyFrameNumber;
1081         if (it.key().startsWith("#")) {
1082             currentKeyFrameNumber = it.key().section(":", 0, 0);
1083             if (currentKeyFrameNumber != keyFrameNumber) {
1084                 // attach filter to the clip
1085                 clipService.attach(*filter);
1086                 filter = new Mlt::Filter(*m_mltProfile, filterId);
1087                 filter->set("kdenlive_id", filterId);
1088                 keyFrameNumber = currentKeyFrameNumber;
1089             }
1090             key = it.key().section(":", 1);
1091         } else key = it.key();
1092         char *name = decodedString(key);
1093         char *value = decodedString(it.value());
1094         filter->set(name, value);
1095         delete[] name;
1096         delete[] value;
1097     }
1098     // attach filter to the clip
1099     clipService.attach(*filter);
1100     delete[] filterId;
1101     m_isBlocked = false;
1102     if (doRefresh) refresh();
1103
1104 }
1105
1106 void Render::mltEditEffect(int track, GenTime position, QMap <QString, QString> args) {
1107     QString index = args.value("kdenlive_ix");
1108     QString tag =  args.value("tag");
1109     QMap<QString, QString>::Iterator it = args.begin();
1110     if (it.key().startsWith("#") || tag.startsWith("ladspa") || tag == "sox" || tag == "autotrack_rectangle") {
1111         // This is a keyframe effect, to edit it, we remove it and re-add it.
1112         mltRemoveEffect(track, position, index);
1113         mltAddEffect(track, position, args);
1114         return;
1115     }
1116     m_isBlocked = true;
1117     // create filter
1118     Mlt::Service service(m_mltProducer->parent().get_service());
1119
1120     Mlt::Tractor tractor(service);
1121     Mlt::Producer trackProducer(tractor.track(track));
1122     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1123     //int clipIndex = trackPlaylist.get_clip_index_at(position.frames(m_fps));
1124     Mlt::Producer *clip = trackPlaylist.get_clip_at(position.frames(m_fps));
1125     if (!clip) {
1126         kDebug() << "WARINIG, CANNOT FIND CLIP ON track: " << track << ", AT POS: " << position.frames(m_fps);
1127         m_isBlocked = false;
1128         return;
1129     }
1130
1131     Mlt::Service clipService(clip->get_service());
1132
1133 //    if (tag.startsWith("ladspa")) tag = "ladspa";
1134
1135     int ct = 0;
1136     Mlt::Filter *filter = clipService.filter(ct);
1137     while (filter) {
1138         if (filter->get("kdenlive_ix") == index) {
1139             break;
1140         }
1141         ct++;
1142         filter = clipService.filter(ct);
1143     }
1144
1145
1146     if (!filter) {
1147         kDebug() << "WARINIG, FILTER FOR EDITING NOT FOUND, ADDING IT!!!!!";
1148         mltAddEffect(track, position, args);
1149         m_isBlocked = false;
1150         return;
1151     }
1152
1153     for (it = args.begin(); it != args.end(); ++it) {
1154         kDebug() << " / / EDITING EFFECT ARGS: " << it.key() << ": " << it.value();
1155         char *name = decodedString(it.key());
1156         char *value = decodedString(it.value());
1157         filter->set(name, value);
1158         delete[] name;
1159         delete[] value;
1160     }
1161     m_isBlocked = false;
1162     refresh();
1163 }
1164
1165 void Render::mltResizeClipEnd(int track, GenTime pos, GenTime in, GenTime out) {
1166     m_isBlocked = true;
1167     Mlt::Service service(m_mltProducer->parent().get_service());
1168
1169     Mlt::Tractor tractor(service);
1170     Mlt::Producer trackProducer(tractor.track(track));
1171     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1172     if (trackPlaylist.is_blank_at(pos.frames(m_fps) + 1))
1173         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1174     int clipIndex = trackPlaylist.get_clip_index_at(pos.frames(m_fps) + 1);
1175
1176     int previousDuration = trackPlaylist.clip_length(clipIndex) - 1;
1177     int newDuration = out.frames(m_fps) - 1;
1178
1179     kDebug() << " ** RESIZING CLIP END:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", in: " << in.frames(25) << ", out: " << out.frames(25) << ", PREVIOUS duration: " << previousDuration;
1180     trackPlaylist.resize_clip(clipIndex, in.frames(m_fps), newDuration);
1181     trackPlaylist.consolidate_blanks(0);
1182     if (previousDuration < newDuration) {
1183         // clip was made longer, trim next blank if there is one.
1184         if (trackPlaylist.is_blank(clipIndex + 1)) {
1185             trackPlaylist.split(clipIndex + 1, newDuration - previousDuration);
1186             trackPlaylist.remove(clipIndex + 1);
1187         }
1188     } else trackPlaylist.insert_blank(clipIndex + 1, previousDuration - newDuration - 1);
1189
1190     trackPlaylist.consolidate_blanks(0);
1191     tractor.multitrack()->refresh();
1192     tractor.refresh();
1193     if (track != 0) mltCheckLength();
1194     m_isBlocked = false;
1195 }
1196
1197 void Render::mltChangeTrackState(int track, bool mute, bool blind) {
1198     Mlt::Service service(m_mltProducer->parent().get_service());
1199
1200     Mlt::Tractor tractor(service);
1201     Mlt::Producer trackProducer(tractor.track(track));
1202     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1203     if (mute) {
1204         if (blind) trackProducer.set("hide", 3);
1205         else trackProducer.set("hide", 2);
1206     } else if (blind) {
1207         trackProducer.set("hide", 1);
1208     } else {
1209         trackProducer.set("hide", 0);
1210     }
1211     tractor.multitrack()->refresh();
1212     tractor.refresh();
1213     refresh();
1214 }
1215
1216 void Render::mltResizeClipStart(int track, GenTime pos, GenTime moveEnd, GenTime moveStart, GenTime in, GenTime out) {
1217     m_isBlocked = true;
1218     Mlt::Service service(m_mltProducer->parent().get_service());
1219     int moveFrame = (moveEnd - moveStart).frames(m_fps);
1220
1221     Mlt::Tractor tractor(service);
1222     Mlt::Producer trackProducer(tractor.track(track));
1223     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1224     if (trackPlaylist.is_blank_at(pos.frames(m_fps) - 1))
1225         kDebug() << "////////  ERROR RSIZING BLANK CLIP!!!!!!!!!!!";
1226     int clipIndex = trackPlaylist.get_clip_index_at(pos.frames(m_fps) - 1);
1227     kDebug() << " ** RESIZING CLIP START:" << clipIndex << " on track:" << track << ", mid pos: " << pos.frames(25) << ", moving: " << moveFrame << ", in: " << in.frames(25) << ", out: " << out.frames(25);
1228
1229     trackPlaylist.resize_clip(clipIndex, in.frames(m_fps), out.frames(m_fps));
1230     if (moveFrame > 0) trackPlaylist.insert_blank(clipIndex, moveFrame - 1);
1231     else {
1232         int midpos = moveStart.frames(m_fps) - 1; //+ (moveFrame / 2)
1233         int blankIndex = trackPlaylist.get_clip_index_at(midpos);
1234         int blankLength = trackPlaylist.clip_length(blankIndex);
1235
1236         kDebug() << " + resizing blank: " << blankIndex << ", Mid: " << midpos << ", Length: " << blankLength << ", SIZE DIFF: " << moveFrame;
1237
1238
1239         if (blankLength + moveFrame == 0) trackPlaylist.remove(blankIndex);
1240         else trackPlaylist.resize_clip(blankIndex, 0, blankLength + moveFrame - 1);
1241     }
1242     trackPlaylist.consolidate_blanks(0);
1243     m_isBlocked = false;
1244     kDebug() << "-----------------\n" << "CLIP 0: " << trackPlaylist.clip_start(0) << ", LENGT: " << trackPlaylist.clip_length(0);
1245     kDebug() << "CLIP 1: " << trackPlaylist.clip_start(1) << ", LENGT: " << trackPlaylist.clip_length(1);
1246     kDebug() << "CLIP 2: " << trackPlaylist.clip_start(2) << ", LENGT: " << trackPlaylist.clip_length(2);
1247     kDebug() << "CLIP 3: " << trackPlaylist.clip_start(3) << ", LENGT: " << trackPlaylist.clip_length(3);
1248     kDebug() << "CLIP 4: " << trackPlaylist.clip_start(4) << ", LENGT: " << trackPlaylist.clip_length(4);
1249 }
1250
1251 void Render::mltMoveClip(int startTrack, int endTrack, GenTime moveStart, GenTime moveEnd) {
1252     mltMoveClip(startTrack, endTrack, (int) moveStart.frames(m_fps), (int) moveEnd.frames(m_fps));
1253 }
1254
1255
1256 void Render::mltMoveClip(int startTrack, int endTrack, int moveStart, int moveEnd) {
1257     m_isBlocked = true;
1258     //m_mltConsumer->set("refresh", 0);
1259     Mlt::Service service(m_mltProducer->parent().get_service());
1260
1261     Mlt::Tractor tractor(service);
1262     Mlt::Producer trackProducer(tractor.track(startTrack));
1263     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
1264     int clipIndex = trackPlaylist.get_clip_index_at(moveStart + 1);
1265     mlt_field field = mlt_tractor_field(tractor.get_tractor());
1266     mlt_multitrack multitrack = mlt_field_multitrack(field); //mlt_tractor_multitrack(tractor.get_tractor());
1267     kDebug() << " --  CURRENT MULTIOTRACK HAS: " << mlt_multitrack_count(multitrack) << " tracks";;
1268     mlt_service multiprod = mlt_multitrack_service(multitrack);
1269
1270     Mlt::Producer clipProducer(trackPlaylist.replace_with_blank(clipIndex));
1271     trackPlaylist.consolidate_blanks(0);
1272     mlt_events_block(MLT_PRODUCER_PROPERTIES(trackProducer.get_producer()), NULL);
1273
1274     if (endTrack == startTrack) {
1275         if (!trackPlaylist.is_blank_at(moveEnd)) {
1276             kWarning() << "// ERROR, CLIP COLLISION----------";
1277             int ix = trackPlaylist.get_clip_index_at(moveEnd);
1278             kDebug() << "BAD CLIP STARTS AT: " << trackPlaylist.clip_start(ix) << ", LENGT: " << trackPlaylist.clip_length(ix);
1279         }
1280         trackPlaylist.insert_at(moveEnd, clipProducer, 1);
1281         trackPlaylist.consolidate_blanks(0);
1282     } else {
1283         trackPlaylist.consolidate_blanks(0);
1284         Mlt::Producer destTrackProducer(tractor.track(endTrack));
1285         Mlt::Playlist destTrackPlaylist((mlt_playlist) destTrackProducer.get_service());
1286         destTrackPlaylist.consolidate_blanks(1);
1287         destTrackPlaylist.insert_at(moveEnd, clipProducer, 1);
1288         destTrackPlaylist.consolidate_blanks(0);
1289     }
1290
1291     mltCheckLength();
1292     mlt_events_unblock(MLT_PRODUCER_PROPERTIES(trackProducer.get_producer()), NULL);
1293     m_isBlocked = false;
1294     m_mltConsumer->set("refresh", 1);
1295 }
1296
1297 void Render::mltMoveTransition(QString type, int startTrack, int trackOffset, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut) {
1298     m_isBlocked = true;
1299     m_mltConsumer->set("refresh", 0);
1300     mlt_service serv = m_mltProducer->parent().get_service();
1301
1302     mlt_service nextservice = mlt_service_get_producer(serv);
1303     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
1304     QString mlt_type = mlt_properties_get(properties, "mlt_type");
1305     QString resource = mlt_properties_get(properties, "mlt_service");
1306     int old_pos = (oldIn.frames(m_fps) + oldOut.frames(m_fps)) / 2;
1307
1308     int new_in = newIn.frames(m_fps);
1309     int new_out = newOut.frames(m_fps) - 1;
1310     while (mlt_type == "transition") {
1311         mlt_transition tr = (mlt_transition) nextservice;
1312         int currentTrack = mlt_transition_get_b_track(tr);
1313         int currentIn = (int) mlt_transition_get_in(tr);
1314         int currentOut = (int) mlt_transition_get_out(tr);
1315         kDebug() << "// FOUND EXISTING TRANS, IN: " << currentIn << ", OUT: " << currentOut << ", TRACK: " << currentTrack;
1316         //kDebug()<<"// LOOKING FOR IN: "<<old_in<<", OUT: "<<old_out;
1317         kDebug() << "// OLD IN: " << oldIn.frames(m_fps) << " // OLD OUT: " << oldOut.frames(m_fps) << ", TRACK: " << startTrack << ", MID POS: " << old_pos;
1318         if (resource == type && startTrack == currentTrack && currentIn <= old_pos && currentOut >= old_pos) {
1319             mlt_transition_set_in_and_out(tr, new_in, new_out);
1320             if (trackOffset != 0) {
1321                 mlt_properties properties = MLT_TRANSITION_PROPERTIES(tr);
1322                 mlt_properties_set_int(properties, "a_track", mlt_transition_get_a_track(tr) + trackOffset);
1323                 mlt_properties_set_int(properties, "b_track", mlt_transition_get_b_track(tr) + trackOffset);
1324             }
1325             break;
1326         }
1327         nextservice = mlt_service_producer(nextservice);
1328         properties = MLT_SERVICE_PROPERTIES(nextservice);
1329         mlt_type = mlt_properties_get(properties, "mlt_type");
1330         resource = mlt_properties_get(properties, "mlt_service");
1331     }
1332     m_isBlocked = false;
1333 }
1334
1335 void Render::mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QMap <QString, QString> args) {
1336     m_isBlocked = true;
1337     Mlt::Service service(m_mltProducer->parent().get_service());
1338
1339     Mlt::Tractor tractor(service);
1340     Mlt::Field *field = tractor.field();
1341     char *transId = decodedString(tag);
1342     Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, transId);
1343     transition->set_in_and_out((int) in.frames(m_fps), (int) out.frames(m_fps));
1344     QMap<QString, QString>::Iterator it;
1345     QString key;
1346
1347     kDebug() << " ------  ADDING TRANSITION PARAMs: " << args.count();
1348
1349     for (it = args.begin(); it != args.end(); ++it) {
1350         key = it.key();
1351         char *name = decodedString(key);
1352         char *value = decodedString(it.value());
1353         transition->set(name, value);
1354         kDebug() << " ------  ADDING TRANS PARAM: " << name << ": " << value;
1355         //filter->set("kdenlive_id", id);
1356         delete[] name;
1357         delete[] value;
1358     }
1359     // attach filter to the clip
1360     field->plant_transition(*transition, a_track, b_track);
1361     delete[] transId;
1362     m_isBlocked = false;
1363     refresh();
1364
1365 }
1366
1367 void Render::mltSavePlaylist() {
1368     kWarning() << "// UPDATING PLAYLIST TO DISK++++++++++++++++";
1369     Mlt::Consumer *fileConsumer = new Mlt::Consumer(*m_mltProfile, "westley");
1370     fileConsumer->set("resource", "/home/one/playlist.xml");
1371
1372     Mlt::Service service(m_mltProducer->get_service());
1373     Mlt::Tractor tractor(service);
1374
1375     fileConsumer->connect(service);
1376     fileConsumer->start();
1377
1378 }
1379
1380 #include "renderer.moc"