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