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