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