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