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