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