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