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