]> git.sesse.net Git - kdenlive/blob - src/docclipbase.cpp
Merge branch 'next' into audioAlign
[kdenlive] / src / docclipbase.cpp
1 /***************************************************************************
2  *                         DocClipBase.cpp  -  description                 *
3  *                           -------------------                           *
4  *   begin                : Fri Apr 12 2002                                *
5  *   Copyright (C) 2002 by Jason Wood (jasonwood@blueyonder.co.uk)         *
6  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
22  ***************************************************************************/
23
24
25
26
27 #include "docclipbase.h"
28 #include "kdenlivesettings.h"
29 #include "kthumb.h"
30 #include "clipmanager.h"
31 #include "slideshowclip.h"
32
33 #include <KIO/NetAccess>
34 #include <KStandardDirs>
35 #include <KDebug>
36
37 #include <QCryptographicHash>
38 #include <QtConcurrentRun>
39
40 #include <cstdio>
41
42 DocClipBase::DocClipBase(ClipManager *clipManager, QDomElement xml, const QString &id) :
43         QObject(),
44         m_audioFrameCache(),
45         m_refcount(0),
46         m_baseTrackProducers(),
47         m_audioTrackProducers(),
48         m_videoOnlyProducer(NULL),
49         m_snapMarkers(QList < CommentedTime >()),
50         m_duration(),
51         m_thumbProd(NULL),
52         m_audioThumbCreated(false),
53         m_id(id),
54         m_placeHolder(xml.hasAttribute("placeholder")),
55         m_properties()
56 {
57     int type = xml.attribute("type").toInt();
58     m_clipType = (CLIPTYPE) type;
59     if (m_placeHolder) xml.removeAttribute("placeholder");
60     QDomNamedNodeMap attributes = xml.attributes();
61     for (int i = 0; i < attributes.count(); i++) {
62         QString name = attributes.item(i).nodeName();
63         if (name.startsWith("meta.attr.")) {
64             m_metadata.insert(name.section('.', 2, 3), attributes.item(i).nodeValue());
65         } else m_properties.insert(name, attributes.item(i).nodeValue());
66     }
67
68     if (xml.hasAttribute("cutzones")) {
69         QStringList cuts = xml.attribute("cutzones").split(";", QString::SkipEmptyParts);
70         for (int i = 0; i < cuts.count(); i++) {
71             QString z = cuts.at(i);
72             addCutZone(z.section('-', 0, 0).toInt(), z.section('-', 1, 1).toInt(), z.section('-', 2, 2));
73         }
74     }
75
76     KUrl url = KUrl(xml.attribute("resource"));
77     if (!m_properties.contains("file_hash") && !url.isEmpty()) getFileHash(url.path());
78
79     if (xml.hasAttribute("duration")) {
80         setDuration(GenTime(xml.attribute("duration").toInt(), KdenliveSettings::project_fps()));
81     } else {
82         int out = xml.attribute("out").toInt();
83         int in = xml.attribute("in").toInt();
84         setDuration(GenTime(out - in, KdenliveSettings::project_fps()));
85     }
86
87     if (!m_properties.contains("name")) m_properties.insert("name", url.fileName());
88
89     m_thumbProd = new KThumb(clipManager, url, m_id, m_properties.value("file_hash"));
90     
91     // Setup timer to trigger audio thumbs creation
92     m_audioTimer.setSingleShot(true);
93     m_audioTimer.setInterval(800);
94     connect(&m_audioTimer, SIGNAL(timeout()), m_thumbProd, SLOT(slotCreateAudioThumbs()));
95     
96 }
97
98 DocClipBase::~DocClipBase()
99 {
100     m_audioTimer.stop();
101     delete m_thumbProd;
102     m_thumbProd = NULL;
103     qDeleteAll(m_toDeleteProducers);
104     m_toDeleteProducers.clear();
105     qDeleteAll(m_baseTrackProducers);
106     m_baseTrackProducers.clear();
107     qDeleteAll(m_audioTrackProducers);
108     m_audioTrackProducers.clear();
109     delete m_videoOnlyProducer;
110     m_videoOnlyProducer = NULL;
111 }
112
113 void DocClipBase::setZone(QPoint zone)
114 {
115     m_properties.insert("zone_in", QString::number(zone.x()));
116     m_properties.insert("zone_out", QString::number(zone.y()));
117 }
118
119 QPoint DocClipBase::zone() const
120 {
121     QPoint zone(m_properties.value("zone_in", "0").toInt(), m_properties.value("zone_out", "50").toInt());
122     return zone;
123 }
124
125
126 bool DocClipBase::hasAudioThumb() const
127 {
128     if (m_clipType == AUDIO || m_clipType == AV || m_clipType == PLAYLIST) return true;
129     return false;
130 }
131
132 void DocClipBase::slotClearAudioCache()
133 {
134     m_audioFrameCache.clear();
135     m_audioThumbCreated = false;
136 }
137
138 /*void DocClipBase::getClipMainThumb() {
139     if (m_thumbProd) m_thumbProd->getMainThumb(m_properties.value("thumbnail").toInt());
140 }*/
141
142 KThumb *DocClipBase::thumbProducer()
143 {
144     return m_thumbProd;
145 }
146
147 bool DocClipBase::audioThumbCreated() const
148 {
149     return m_audioThumbCreated;
150 }
151
152 const QString DocClipBase::name() const
153 {
154
155     return m_properties.value("name");
156 }
157
158 const QString &DocClipBase::getId() const
159 {
160     return m_id;
161 }
162
163 const CLIPTYPE & DocClipBase::clipType() const
164 {
165     return m_clipType;
166 }
167
168 void DocClipBase::setClipType(CLIPTYPE type)
169 {
170     m_clipType = type;
171     m_properties.insert("type", QString::number((int) type));
172 }
173
174 KUrl DocClipBase::fileURL() const
175 {
176     QString res = m_properties.value("resource");
177     if (m_clipType != COLOR && !res.isEmpty()) return KUrl(res);
178     return KUrl();
179 }
180
181 void DocClipBase::setClipThumbFrame(const uint &ix)
182 {
183     m_properties.insert("thumbnail", QString::number((int) ix));
184 }
185
186 uint DocClipBase::getClipThumbFrame() const
187 {
188     return (uint) m_properties.value("thumbnail").toInt();
189 }
190
191 const QString DocClipBase::description() const
192 {
193     return m_properties.value("description");
194 }
195
196 bool DocClipBase::isTransparent() const
197 {
198     return (m_properties.value("transparency") == "1");
199 }
200
201 const QString DocClipBase::getProperty(const QString &prop) const
202 {
203     return m_properties.value(prop);
204 }
205
206 void DocClipBase::setDuration(GenTime dur)
207 {
208     m_duration = dur;
209     m_properties.insert("duration", QString::number((int) dur.frames(KdenliveSettings::project_fps())));
210 }
211
212 const GenTime &DocClipBase::duration() const
213 {
214     return m_duration;
215 }
216
217 const GenTime DocClipBase::maxDuration() const
218 {
219     if (m_clipType == COLOR || m_clipType == IMAGE || m_clipType == TEXT || (m_clipType == SLIDESHOW &&  m_properties.value("loop") == "1")) {
220         /*const GenTime dur(15000, KdenliveSettings::project_fps());
221         return dur;*/
222         return GenTime();
223     }
224     return m_duration;
225 }
226
227 bool DocClipBase::hasFileSize() const
228 {
229     return true;
230 }
231
232 qulonglong DocClipBase::fileSize() const
233 {
234     return m_properties.value("file_size").toULongLong();
235 }
236
237 // virtual
238 QDomElement DocClipBase::toXML(bool hideTemporaryProperties) const
239 {
240     QDomDocument doc;
241     QDomElement clip = doc.createElement("producer");
242
243     QMapIterator<QString, QString> i(m_properties);
244     while (i.hasNext()) {
245         i.next();
246         if (hideTemporaryProperties && i.key().startsWith("_")) continue;
247         if (!i.value().isEmpty()) clip.setAttribute(i.key(), i.value());
248     }
249     doc.appendChild(clip);
250     if (!m_cutZones.isEmpty()) {
251         QStringList cuts;
252         for (int i = 0; i < m_cutZones.size(); i++) {
253             CutZoneInfo info = m_cutZones.at(i);
254             cuts << QString::number(info.zone.x()) + "-" + QString::number(info.zone.y()) + "-" + info.description;
255         }
256         clip.setAttribute("cutzones", cuts.join(";"));
257     }
258     //kDebug() << "/// CLIP XML: " << doc.toString();
259     return doc.documentElement();
260 }
261
262
263 void DocClipBase::setAudioThumbCreated(bool isDone)
264 {
265     m_audioThumbCreated = isDone;
266 }
267
268 void DocClipBase::updateAudioThumbnail(const audioByteArray& data)
269 {
270     //kDebug() << "CLIPBASE RECIEDVED AUDIO DATA*********************************************";
271     m_audioFrameCache = data;
272     m_audioThumbCreated = true;
273     emit gotAudioData();
274 }
275
276 QList < GenTime > DocClipBase::snapMarkers() const
277 {
278     QList < GenTime > markers;
279
280     for (int count = 0; count < m_snapMarkers.count(); ++count) {
281         markers.append(m_snapMarkers.at(count).time());
282     }
283
284     return markers;
285 }
286
287 QList < CommentedTime > DocClipBase::commentedSnapMarkers() const
288 {
289     return m_snapMarkers;
290 }
291
292
293 void DocClipBase::addSnapMarker(const GenTime & time, QString comment)
294 {
295     QList < CommentedTime >::Iterator it = m_snapMarkers.begin();
296     for (it = m_snapMarkers.begin(); it != m_snapMarkers.end(); ++it) {
297         if ((*it).time() >= time)
298             break;
299     }
300
301     if ((it != m_snapMarkers.end()) && ((*it).time() == time)) {
302         (*it).setComment(comment);
303         //kError() << "trying to add Snap Marker that already exists, this will cause inconsistancies with undo/redo";
304     } else {
305         CommentedTime t(time, comment);
306         m_snapMarkers.insert(it, t);
307     }
308
309 }
310
311 void DocClipBase::editSnapMarker(const GenTime & time, QString comment)
312 {
313     QList < CommentedTime >::Iterator it;
314     for (it = m_snapMarkers.begin(); it != m_snapMarkers.end(); ++it) {
315         if ((*it).time() == time)
316             break;
317     }
318     if (it != m_snapMarkers.end()) {
319         (*it).setComment(comment);
320     } else {
321         kError() << "trying to edit Snap Marker that does not already exists";
322     }
323 }
324
325 QString DocClipBase::deleteSnapMarker(const GenTime & time)
326 {
327     QString result = i18n("Marker");
328     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
329
330     while (itt != m_snapMarkers.end()) {
331         if ((*itt).time() == time)
332             break;
333         ++itt;
334     }
335
336     if ((itt != m_snapMarkers.end()) && ((*itt).time() == time)) {
337         result = (*itt).comment();
338         m_snapMarkers.erase(itt);
339     }
340     return result;
341 }
342
343
344 GenTime DocClipBase::hasSnapMarkers(const GenTime & time)
345 {
346     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
347
348     while (itt != m_snapMarkers.end()) {
349         if ((*itt).time() == time)
350             return time;
351         ++itt;
352     }
353
354     return GenTime(0.0);
355 }
356
357 GenTime DocClipBase::findPreviousSnapMarker(const GenTime & currTime)
358 {
359     int it;
360     for (it = 0; it < m_snapMarkers.count(); it++) {
361         if (m_snapMarkers.at(it).time() >= currTime)
362             break;
363     }
364     if (it == 0) return GenTime();
365     else if (it == m_snapMarkers.count() - 1 && m_snapMarkers.at(it).time() < currTime)
366         return m_snapMarkers.at(it).time();
367     else return m_snapMarkers.at(it - 1).time();
368 }
369
370 GenTime DocClipBase::findNextSnapMarker(const GenTime & currTime)
371 {
372     int it;
373     for (it = 0; it < m_snapMarkers.count(); it++) {
374         if (m_snapMarkers.at(it).time() > currTime)
375             break;
376     }
377     if (it < m_snapMarkers.count() && m_snapMarkers.at(it).time() > currTime) return m_snapMarkers.at(it).time();
378     return duration();
379 }
380
381 QString DocClipBase::markerComment(GenTime t)
382 {
383     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
384
385     while (itt != m_snapMarkers.end()) {
386         if ((*itt).time() == t)
387             return (*itt).comment();
388         ++itt;
389     }
390     return QString();
391 }
392
393 void DocClipBase::clearThumbProducer()
394 {
395     if (m_thumbProd) m_thumbProd->clearProducer();
396 }
397
398 void DocClipBase::reloadThumbProducer()
399 {
400     if (m_thumbProd && !m_thumbProd->hasProducer())
401         m_thumbProd->setProducer(getProducer());
402 }
403
404 void DocClipBase::deleteProducers()
405 {
406     if (m_thumbProd) m_thumbProd->clearProducer();
407     
408     if (numReferences() > 0) {
409         // Clip is used in timeline, delay producers deletion
410         if (m_videoOnlyProducer) m_toDeleteProducers.append(m_videoOnlyProducer);
411         for (int i = 0; i < m_baseTrackProducers.count(); i++) {
412             m_toDeleteProducers.append(m_baseTrackProducers.at(i));
413         }
414         for (int i = 0; i < m_audioTrackProducers.count(); i++) {
415             m_toDeleteProducers.append(m_audioTrackProducers.at(i));
416         }
417     }
418     else {
419         delete m_videoOnlyProducer;
420         qDeleteAll(m_baseTrackProducers);
421         qDeleteAll(m_audioTrackProducers);
422         m_replaceMutex.unlock();
423     }
424     m_videoOnlyProducer = NULL;
425     m_baseTrackProducers.clear();
426     m_audioTrackProducers.clear();
427 }
428
429 void DocClipBase::cleanupProducers()
430 {
431     /*
432     int ct = 0;
433     kDebug()<<"----------------------------------------------------------------------------------";
434     for (int i = 0; i < m_toDeleteProducers.count(); i++) {
435         if (m_toDeleteProducers.at(i) != NULL) {
436             Mlt::Properties props(m_toDeleteProducers.at(i)->get_properties());
437             if (props.ref_count() > 2) {
438                 kDebug()<<"PRODUCER: "<<i<<", COUNTS: "<<props.ref_count();
439                 //exit(1);
440             }
441             ct++;
442         }
443     }*/
444
445     if (!isClean()) {
446       qDeleteAll(m_toDeleteProducers);
447       m_toDeleteProducers.clear();
448       m_replaceMutex.unlock();
449     }
450 }
451
452 bool DocClipBase::isClean() const
453 {
454     return m_toDeleteProducers.isEmpty();
455 }
456
457 void DocClipBase::setValid()
458 {
459     m_placeHolder = false;
460 }
461
462 void DocClipBase::setProducer(Mlt::Producer *producer, bool reset, bool readPropertiesFromProducer)
463 {
464     if (producer == NULL) return;
465     if (reset) {
466         QMutexLocker locker(&m_producerMutex);
467         m_replaceMutex.lock();
468         deleteProducers();
469     }
470     QString id = producer->get("id");
471     if (m_placeHolder || !producer->is_valid()) {
472         char *tmp = qstrdup(i18n("Missing clip").toUtf8().constData());
473         producer->set("markup", tmp);
474         producer->set("bgcolour", "0xff0000ff");
475         producer->set("pad", "10");
476         delete[] tmp;
477     }
478     else if (m_thumbProd && !m_thumbProd->hasProducer()) {
479         if (m_clipType != AUDIO) {
480             if (!id.endsWith("_audio"))
481                 m_thumbProd->setProducer(producer);
482         }
483         else m_thumbProd->setProducer(producer);
484         getAudioThumbs();
485     }
486     bool updated = false;
487     if (id.contains('_')) {
488         // this is a subtrack producer, insert it at correct place
489         id = id.section('_', 1);
490         if (id.endsWith("audio")) {
491             int pos = id.section('_', 0, 0).toInt();
492             if (pos >= m_audioTrackProducers.count()) {
493                 while (m_audioTrackProducers.count() - 1 < pos) {
494                     m_audioTrackProducers.append(NULL);
495                 }
496             }
497             if (m_audioTrackProducers.at(pos) == NULL) {
498                 m_audioTrackProducers[pos] = producer;
499                 updated = true;
500             }
501             else delete producer;
502             return;
503         } else if (id.endsWith("video")) {
504             if (m_videoOnlyProducer == NULL) {
505                 m_videoOnlyProducer = producer;
506                 updated = true;
507             }
508             else delete producer;
509             return;
510         }
511         int pos = id.toInt();
512         if (pos >= m_baseTrackProducers.count()) {
513             while (m_baseTrackProducers.count() - 1 < pos) {
514                 m_baseTrackProducers.append(NULL);
515             }
516         }
517         if (m_baseTrackProducers.at(pos) == NULL) {
518             m_baseTrackProducers[pos] = producer;
519             updated = true;
520         }
521         else delete producer;
522     } else {
523         if (m_baseTrackProducers.isEmpty()) {
524             m_baseTrackProducers.append(producer);
525             updated = true;
526         }
527         else if (m_baseTrackProducers.at(0) == NULL) {
528             m_baseTrackProducers[0] = producer;
529             updated = true;
530         }
531         else delete producer;
532     }
533     if (updated && readPropertiesFromProducer && (m_clipType != COLOR && m_clipType != IMAGE && m_clipType != TEXT))
534         setDuration(GenTime(producer->get_length(), KdenliveSettings::project_fps()));
535 }
536
537 static double getPixelAspect(QMap<QString, QString>& props) {
538     int width = props.value("frame_size").section('x', 0, 0).toInt();
539     int height = props.value("frame_size").section('x', 1, 1).toInt();
540     int aspectNumerator = props.value("force_aspect_num").toInt();
541     int aspectDenominator = props.value("force_aspect_den").toInt();
542     if (aspectDenominator != 0 && width != 0)
543         return double(height) * aspectNumerator / aspectDenominator / width;    
544     else
545         return 1.0;
546 }
547
548 Mlt::Producer *DocClipBase::audioProducer(int track)
549 {
550     QMutexLocker locker(&m_producerMutex);
551     if (m_audioTrackProducers.count() <= track) {
552         while (m_audioTrackProducers.count() - 1 < track) {
553             m_audioTrackProducers.append(NULL);
554         }
555     }
556     if (m_audioTrackProducers.at(track) == NULL) {
557         int i;
558         for (i = 0; i < m_audioTrackProducers.count(); i++)
559             if (m_audioTrackProducers.at(i) != NULL) break;
560         Mlt::Producer *base;
561         if (i >= m_audioTrackProducers.count()) {
562             // Could not find a valid producer for that clip
563             locker.unlock();
564             base = getProducer();
565             if (base == NULL) {
566                 return NULL;
567             }
568             locker.relock();
569         }
570         else base = m_audioTrackProducers.at(i);
571         m_audioTrackProducers[track] = cloneProducer(base);
572         adjustProducerProperties(m_audioTrackProducers.at(track), QString(getId() + '_' + QString::number(track) + "_audio"), false, true);
573     }
574     return m_audioTrackProducers.at(track);
575 }
576
577
578 void DocClipBase::adjustProducerProperties(Mlt::Producer *prod, const QString &id, bool mute, bool blind)
579 {
580         if (m_properties.contains("force_aspect_num") && m_properties.contains("force_aspect_den") && m_properties.contains("frame_size"))
581             prod->set("force_aspect_ratio", getPixelAspect(m_properties));
582         if (m_properties.contains("force_fps")) prod->set("force_fps", m_properties.value("force_fps").toDouble());
583         if (m_properties.contains("force_progressive")) prod->set("force_progressive", m_properties.value("force_progressive").toInt());
584         if (m_properties.contains("force_tff")) prod->set("force_tff", m_properties.value("force_tff").toInt());
585         if (m_properties.contains("threads")) prod->set("threads", m_properties.value("threads").toInt());
586         if (mute) prod->set("audio_index", -1);
587         else if (m_properties.contains("audio_index")) prod->set("audio_index", m_properties.value("audio_index").toInt());
588         if (blind) prod->set("video_index", -1);
589         else if (m_properties.contains("video_index")) prod->set("video_index", m_properties.value("video_index").toInt());
590         prod->set("id", id.toUtf8().constData());
591         if (m_properties.contains("force_colorspace")) prod->set("force_colorspace", m_properties.value("force_colorspace").toInt());
592         if (m_properties.contains("full_luma")) prod->set("set.force_full_luma", m_properties.value("full_luma").toInt());
593         if (m_properties.contains("proxy_out")) {
594             // We have a proxy clip, make sure the proxy has same duration as original
595             prod->set("length", m_properties.value("duration").toInt());
596             prod->set("out", m_properties.value("proxy_out").toInt());
597         }
598
599 }
600
601 Mlt::Producer *DocClipBase::videoProducer()
602 {
603     QMutexLocker locker(&m_producerMutex);
604     if (m_videoOnlyProducer == NULL) {
605         int i;
606         for (i = 0; i < m_baseTrackProducers.count(); i++)
607             if (m_baseTrackProducers.at(i) != NULL) break;
608         if (i >= m_baseTrackProducers.count()) return NULL;
609         m_videoOnlyProducer = cloneProducer(m_baseTrackProducers.at(i));
610         adjustProducerProperties(m_videoOnlyProducer, QString(getId() + "_video"), true, false);
611     }
612     return m_videoOnlyProducer;
613 }
614
615 Mlt::Producer *DocClipBase::getCloneProducer()
616 {
617     Mlt::Producer *source = NULL;
618     Mlt::Producer *prod = NULL;
619     if (m_clipType != AUDIO && m_clipType != AV && m_clipType != PLAYLIST) {
620         source = getProducer();
621         if (!source) return NULL;
622     }
623     if (m_clipType == COLOR) {
624         prod = new Mlt::Producer(*(source->profile()), 0, QString("colour:" + QString(source->get("resource"))).toUtf8().constData());
625     } else if (m_clipType == TEXT) {
626         prod = new Mlt::Producer(*(source->profile()), 0, QString("kdenlivetitle:" + QString(source->get("resource"))).toUtf8().constData());
627         if (prod && prod->is_valid() && m_properties.contains("xmldata"))
628             prod->set("xmldata", m_properties.value("xmldata").toUtf8().constData());
629     }
630     if (!prod) {
631         if (!source) {
632             QMutexLocker locker(&m_producerMutex);
633             for (int i = 0; i < m_baseTrackProducers.count(); i++) {
634                 if (m_baseTrackProducers.at(i) != NULL) {
635                     source = m_baseTrackProducers.at(i);
636                     break;
637                 }
638             }
639             if (!source) return NULL;
640         }
641         prod = cloneProducer(source);
642     }
643     if (prod) {
644         adjustProducerProperties(prod, getId() + "_", false, false);
645         if (!m_properties.contains("proxy_out")) {
646             // Adjust length in case...
647             if (m_properties.contains("duration")) prod->set("length", m_properties.value("duration").toInt());
648             if (m_properties.contains("out"))prod->set("out", m_properties.value("out").toInt());
649         }
650     }
651     return prod;
652 }
653
654 Mlt::Producer *DocClipBase::getProducer(int track)
655 {
656     QMutexLocker locker(&m_producerMutex);
657     if (track == -1 || (m_clipType != AUDIO && m_clipType != AV && m_clipType != PLAYLIST)) {
658         if (m_baseTrackProducers.count() == 0) {
659             return NULL;
660         }
661         for (int i = 0; i < m_baseTrackProducers.count(); i++) {
662             if (m_baseTrackProducers.at(i) != NULL) {
663                 return m_baseTrackProducers.at(i);
664             }
665         }
666         return NULL;
667     }
668     if (track >= m_baseTrackProducers.count()) {
669         while (m_baseTrackProducers.count() - 1 < track) {
670             m_baseTrackProducers.append(NULL);
671         }
672     }
673     if (m_baseTrackProducers.at(track) == NULL) {
674         int i;
675         for (i = 0; i < m_baseTrackProducers.count(); i++)
676             if (m_baseTrackProducers.at(i) != NULL) break;
677
678         if (i >= m_baseTrackProducers.count()) {
679             // Could not find a valid producer for that clip, check in 
680             return NULL;
681         }
682         Mlt::Producer *prod = cloneProducer(m_baseTrackProducers.at(i));
683         adjustProducerProperties(prod, QString(getId() + '_' + QString::number(track)), false, false);
684         m_baseTrackProducers[track] = prod;
685     }
686     return m_baseTrackProducers.at(track);
687 }
688
689
690 Mlt::Producer *DocClipBase::cloneProducer(Mlt::Producer *source)
691 {
692     Mlt::Producer *result = NULL;
693     QString url = QString::fromUtf8(source->get("resource"));
694     if (m_clipType == SLIDESHOW || KIO::NetAccess::exists(KUrl(url), KIO::NetAccess::SourceSide, 0)) {
695         result = new Mlt::Producer(*(source->profile()), url.toUtf8().constData());
696     }
697     if (result == NULL || !result->is_valid()) {
698         // placeholder clip
699         QString txt = "+" + i18n("Missing clip") + ".txt";
700         char *tmp = qstrdup(txt.toUtf8().constData());
701         result = new Mlt::Producer(*source->profile(), tmp);
702         delete[] tmp;
703         if (result == NULL || !result->is_valid())
704             result = new Mlt::Producer(*(source->profile()), "colour:red");
705         else {
706             result->set("bgcolour", "0xff0000ff");
707             result->set("pad", "10");
708         }
709         return result;
710     }
711     /*Mlt::Properties src_props(source->get_properties());
712     Mlt::Properties props(result->get_properties());
713     props.inherit(src_props);*/
714     return result;
715 }
716
717 void DocClipBase::setProducerProperty(const char *name, int data)
718 {
719     QMutexLocker locker(&m_producerMutex);
720     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
721         if (m_baseTrackProducers.at(i) != NULL)
722             m_baseTrackProducers[i]->set(name, data);
723     }
724 }
725
726 void DocClipBase::setProducerProperty(const char *name, double data)
727 {
728     QMutexLocker locker(&m_producerMutex);
729     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
730         if (m_baseTrackProducers.at(i) != NULL)
731             m_baseTrackProducers[i]->set(name, data);
732     }
733 }
734
735 void DocClipBase::setProducerProperty(const char *name, const char *data)
736 {
737     QMutexLocker locker(&m_producerMutex);
738     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
739         if (m_baseTrackProducers.at(i) != NULL)
740             m_baseTrackProducers[i]->set(name, data);
741     }
742 }
743
744 void DocClipBase::resetProducerProperty(const char *name)
745 {
746     QMutexLocker locker(&m_producerMutex);
747     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
748         if (m_baseTrackProducers.at(i) != NULL)
749             m_baseTrackProducers[i]->set(name, (const char*) NULL);
750     }
751 }
752
753 const char *DocClipBase::producerProperty(const char *name) const
754 {
755     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
756         if (m_baseTrackProducers.at(i) != NULL) {
757             return m_baseTrackProducers.at(i)->get(name);
758         }
759     }
760     return NULL;
761 }
762
763
764 void DocClipBase::slotRefreshProducer()
765 {
766     if (m_baseTrackProducers.count() == 0) return;
767     if (m_clipType == SLIDESHOW) {
768         setProducerProperty("ttl", getProperty("ttl").toInt());
769         //m_clipProducer->set("id", getProperty("id"));
770         if (!getProperty("animation").isEmpty()) {
771             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
772             int ct = 0;
773             Mlt::Filter *filter = clipService.filter(ct);
774             while (filter) {
775                 if (strcmp(filter->get("mlt_service"), "affine") == 0) {
776                     break;
777                 } else if (strcmp(filter->get("mlt_service"), "boxblur") == 0) {
778                     clipService.detach(*filter);
779                 } else ct++;
780                 filter = clipService.filter(ct);
781             }
782
783             if (!filter || strcmp(filter->get("mlt_service"), "affine")) {
784                 // filter does not exist, create it.
785                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "affine");
786                 if (filter && filter->is_valid()) {
787                     int cycle = getProperty("ttl").toInt();
788                     QString geometry = SlideshowClip::animationToGeometry(getProperty("animation"), cycle);
789                     if (!geometry.isEmpty()) {
790                         if (getProperty("animation").contains("low-pass")) {
791                             Mlt::Filter *blur = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "boxblur");
792                             if (blur && blur->is_valid())
793                                 clipService.attach(*blur);
794                         }
795                         filter->set("transition.geometry", geometry.toUtf8().data());
796                         filter->set("transition.cycle", cycle);
797                         clipService.attach(*filter);
798                     }
799                 }
800             }
801         } else {
802             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
803             int ct = 0;
804             Mlt::Filter *filter = clipService.filter(0);
805             while (filter) {
806                 if (strcmp(filter->get("mlt_service"), "affine") == 0 || strcmp(filter->get("mlt_service"), "boxblur") == 0) {
807                     clipService.detach(*filter);
808                 } else ct++;
809                 filter = clipService.filter(ct);
810             }
811         }
812         if (getProperty("fade") == "1") {
813             // we want a fade filter effect
814             kDebug() << "////////////   FADE WANTED";
815             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
816             int ct = 0;
817             Mlt::Filter *filter = clipService.filter(ct);
818             while (filter) {
819                 if (strcmp(filter->get("mlt_service"), "luma") == 0) {
820                     break;
821                 }
822                 ct++;
823                 filter = clipService.filter(ct);
824             }
825
826             if (filter && strcmp(filter->get("mlt_service"), "luma") == 0) {
827                 filter->set("cycle", getProperty("ttl").toInt());
828                 filter->set("duration", getProperty("luma_duration").toInt());
829                 filter->set("luma.resource", getProperty("luma_file").toUtf8().data());
830                 if (!getProperty("softness").isEmpty()) {
831                     int soft = getProperty("softness").toInt();
832                     filter->set("luma.softness", (double) soft / 100.0);
833                 }
834             } else {
835                 // filter does not exist, create it...
836                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "luma");
837                 filter->set("cycle", getProperty("ttl").toInt());
838                 filter->set("duration", getProperty("luma_duration").toInt());
839                 filter->set("luma.resource", getProperty("luma_file").toUtf8().data());
840                 if (!getProperty("softness").isEmpty()) {
841                     int soft = getProperty("softness").toInt();
842                     filter->set("luma.softness", (double) soft / 100.0);
843                 }
844                 clipService.attach(*filter);
845             }
846         } else {
847             kDebug() << "////////////   FADE NOT WANTED!!!";
848             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
849             int ct = 0;
850             Mlt::Filter *filter = clipService.filter(0);
851             while (filter) {
852                 if (strcmp(filter->get("mlt_service"), "luma") == 0) {
853                     clipService.detach(*filter);
854                 } else ct++;
855                 filter = clipService.filter(ct);
856             }
857         }
858         if (getProperty("crop") == "1") {
859             // we want a center crop filter effect
860             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
861             int ct = 0;
862             Mlt::Filter *filter = clipService.filter(ct);
863             while (filter) {
864                 if (strcmp(filter->get("mlt_service"), "crop") == 0) {
865                     break;
866                 }
867                 ct++;
868                 filter = clipService.filter(ct);
869             }
870
871             if (!filter || strcmp(filter->get("mlt_service"), "crop")) {
872                 // filter does not exist, create it...
873                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "crop");
874                 filter->set("center", 1);
875                 clipService.attach(*filter);
876             }
877         } else {
878             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
879             int ct = 0;
880             Mlt::Filter *filter = clipService.filter(0);
881             while (filter) {
882                 if (strcmp(filter->get("mlt_service"), "crop") == 0) {
883                     clipService.detach(*filter);
884                 } else ct++;
885                 filter = clipService.filter(ct);
886             }
887         }
888     }
889 }
890
891 void DocClipBase::setProperties(QMap <QString, QString> properties)
892 {
893     // changing clip type is not allowed
894     properties.remove("type");
895     QMapIterator<QString, QString> i(properties);
896     bool refreshProducer = false;
897     QStringList keys;
898     keys << "luma_duration" << "luma_file" << "fade" << "ttl" << "softness" << "crop" << "animation";
899     QString oldProxy = m_properties.value("proxy");
900     while (i.hasNext()) {
901         i.next();
902         setProperty(i.key(), i.value());
903         if (m_clipType == SLIDESHOW && keys.contains(i.key())) refreshProducer = true;
904     }
905     if (properties.contains("proxy")) {
906         QString value = properties.value("proxy");
907         // If value is "-", that means user manually disabled proxy on this clip
908         if (value.isEmpty() || value == "-") {
909             // reset proxy
910             emit abortProxy(m_id, oldProxy);
911         }
912         else {
913             emit createProxy(m_id);
914         }
915     }
916     if (refreshProducer) slotRefreshProducer();
917 }
918
919 void DocClipBase::setMetadata(QMap <QString, QString> properties)
920 {
921     QMapIterator<QString, QString> i(properties);
922     while (i.hasNext()) {
923         i.next();
924         if (i.value().isEmpty() && m_metadata.contains(i.key())) {
925             m_metadata.remove(i.key());
926         } else {
927             m_metadata.insert(i.key(), i.value());
928         }
929     }
930 }
931
932 QMap <QString, QString> DocClipBase::metadata() const
933 {
934     return m_metadata;
935 }
936
937 void DocClipBase::clearProperty(const QString &key)
938 {
939     m_properties.remove(key);
940 }
941
942 void DocClipBase::getFileHash(const QString &url)
943 {
944     if (m_clipType == SLIDESHOW) return;
945     QFile file(url);
946     if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
947         QByteArray fileData;
948         QByteArray fileHash;
949         //kDebug() << "SETTING HASH of" << value;
950         m_properties.insert("file_size", QString::number(file.size()));
951         /*
952                * 1 MB = 1 second per 450 files (or faster)
953                * 10 MB = 9 seconds per 450 files (or faster)
954                */
955         if (file.size() > 1000000*2) {
956             fileData = file.read(1000000);
957             if (file.seek(file.size() - 1000000))
958                 fileData.append(file.readAll());
959         } else
960             fileData = file.readAll();
961         file.close();
962         fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
963         m_properties.insert("file_hash", QString(fileHash.toHex()));
964     }
965 }
966
967 bool DocClipBase::checkHash() const
968 {
969     KUrl url = fileURL();
970     if (!url.isEmpty() && getClipHash() != getHash(url.path())) return false;
971     return true;
972 }
973
974 QString DocClipBase::getClipHash() const
975 {
976     QString hash;
977     if (m_clipType == SLIDESHOW) hash = QCryptographicHash::hash(m_properties.value("resource").toAscii().data(), QCryptographicHash::Md5).toHex();
978     else if (m_clipType == COLOR) hash = QCryptographicHash::hash(m_properties.value("colour").toAscii().data(), QCryptographicHash::Md5).toHex();
979     else if (m_clipType == TEXT) hash = QCryptographicHash::hash(QString("title" + getId() + m_properties.value("xmldata")).toUtf8().data(), QCryptographicHash::Md5).toHex();
980     else {
981         if (m_properties.contains("file_hash")) hash = m_properties.value("file_hash");
982         if (hash.isEmpty()) hash = getHash(fileURL().path());
983         
984     }
985     return hash;
986 }
987
988 void DocClipBase::setPlaceHolder(bool place)
989 {
990     m_placeHolder = place;
991 }
992
993 // static
994 QString DocClipBase::getHash(const QString &path)
995 {
996     QFile file(path);
997     if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
998         QByteArray fileData;
999         QByteArray fileHash;
1000         /*
1001                * 1 MB = 1 second per 450 files (or faster)
1002                * 10 MB = 9 seconds per 450 files (or faster)
1003                */
1004         if (file.size() > 1000000*2) {
1005             fileData = file.read(1000000);
1006             if (file.seek(file.size() - 1000000))
1007                 fileData.append(file.readAll());
1008         } else
1009             fileData = file.readAll();
1010         file.close();
1011         return QCryptographicHash::hash(fileData, QCryptographicHash::Md5).toHex();
1012     }
1013     return QString();
1014 }
1015
1016 void DocClipBase::refreshThumbUrl()
1017 {
1018     if (m_thumbProd) m_thumbProd->updateThumbUrl(m_properties.value("file_hash"));
1019 }
1020
1021 void DocClipBase::setProperty(const QString &key, const QString &value)
1022 {
1023     m_properties.insert(key, value);
1024     if (key == "resource") {
1025         getFileHash(value);
1026         if (m_thumbProd) m_thumbProd->updateClipUrl(KUrl(value), m_properties.value("file_hash"));
1027     } else if (key == "out") setDuration(GenTime(value.toInt(), KdenliveSettings::project_fps()));
1028     //else if (key == "transparency") m_clipProducer->set("transparency", value.toInt());
1029     else if (key == "colour") {
1030         setProducerProperty("colour", value.toUtf8().data());
1031     } else if (key == "templatetext") {
1032         setProducerProperty("templatetext", value.toUtf8().data());
1033         setProducerProperty("force_reload", 1);
1034     } else if (key == "xmldata") {
1035         setProducerProperty("xmldata", value.toUtf8().data());
1036         setProducerProperty("force_reload", 1);
1037     } else if (key == "force_aspect_num") {
1038         if (value.isEmpty()) {
1039             m_properties.remove("force_aspect_num");
1040             resetProducerProperty("force_aspect_ratio");
1041         } else setProducerProperty("force_aspect_ratio", getPixelAspect(m_properties));
1042     } else if (key == "force_aspect_den") {
1043         if (value.isEmpty()) {
1044             m_properties.remove("force_aspect_den");
1045             resetProducerProperty("force_aspect_ratio");
1046         } else setProducerProperty("force_aspect_ratio", getPixelAspect(m_properties));
1047     } else if (key == "force_fps") {
1048         if (value.isEmpty()) {
1049             m_properties.remove("force_fps");
1050             resetProducerProperty("force_fps");
1051         } else setProducerProperty("force_fps", value.toDouble());
1052     } else if (key == "force_progressive") {
1053         if (value.isEmpty()) {
1054             m_properties.remove("force_progressive");
1055             resetProducerProperty("force_progressive");
1056         } else setProducerProperty("force_progressive", value.toInt());
1057     } else if (key == "force_tff") {
1058         if (value.isEmpty()) {
1059             m_properties.remove("force_tff");
1060             resetProducerProperty("force_tff");
1061         } else setProducerProperty("force_tff", value.toInt());
1062     } else if (key == "threads") {
1063         if (value.isEmpty()) {
1064             m_properties.remove("threads");
1065             setProducerProperty("threads", 1);
1066         } else setProducerProperty("threads", value.toInt());
1067     } else if (key == "video_index") {
1068         if (value.isEmpty()) {
1069             m_properties.remove("video_index");
1070             setProducerProperty("video_index", m_properties.value("default_video").toInt());
1071         } else setProducerProperty("video_index", value.toInt());
1072     } else if (key == "audio_index") {
1073         if (value.isEmpty()) {
1074             m_properties.remove("audio_index");
1075             setProducerProperty("audio_index", m_properties.value("default_audio").toInt());
1076         } else setProducerProperty("audio_index", value.toInt());
1077     } else if (key == "force_colorspace") {
1078         if (value.isEmpty()) {
1079             m_properties.remove("force_colorspace");
1080             resetProducerProperty("force_colorspace");
1081         } else setProducerProperty("force_colorspace", value.toInt());
1082     } else if (key == "full_luma") {
1083         if (value.isEmpty()) {
1084             m_properties.remove("full_luma");
1085             resetProducerProperty("set.force_full_luma");
1086         } else setProducerProperty("set.force_full_luma", value.toInt());
1087     }
1088 }
1089
1090 QMap <QString, QString> DocClipBase::properties() const
1091 {
1092     return m_properties;
1093 }
1094
1095 QMap <QString, QString> DocClipBase::currentProperties(QMap <QString, QString> props)
1096 {
1097     QMap <QString, QString> currentProps;
1098     QMap<QString, QString>::const_iterator i = props.constBegin();
1099     while (i != props.constEnd()) {
1100         currentProps.insert(i.key(), m_properties.value(i.key()));
1101         ++i;
1102     }
1103     return currentProps;
1104 }
1105
1106 bool DocClipBase::getAudioThumbs()
1107 {
1108     if (m_thumbProd == NULL || isPlaceHolder() || !KdenliveSettings::audiothumbnails()) return false;
1109     if (m_audioThumbCreated) {
1110         return false;
1111     }
1112     m_audioTimer.start();
1113     return true;
1114 }
1115
1116 bool DocClipBase::isPlaceHolder() const
1117 {
1118     return m_placeHolder;
1119 }
1120
1121 void DocClipBase::addCutZone(int in, int out, QString desc)
1122 {
1123     CutZoneInfo info;
1124     info.zone = QPoint(in, out);
1125     info.description = desc;
1126     for (int i = 0; i < m_cutZones.count(); i++)
1127         if (m_cutZones.at(i).zone == info.zone) {
1128             return;
1129         }
1130     m_cutZones.append(info);
1131 }
1132
1133 bool DocClipBase::hasCutZone(QPoint p) const
1134 {
1135     for (int i = 0; i < m_cutZones.count(); i++)
1136         if (m_cutZones.at(i).zone == p) return true;
1137     return false;
1138 }
1139
1140
1141 void DocClipBase::removeCutZone(int in, int out)
1142 {
1143     QPoint p(in, out);
1144     for (int i = 0; i < m_cutZones.count(); i++) {
1145         if (m_cutZones.at(i).zone == p) {
1146             m_cutZones.removeAt(i);
1147             i--;
1148         }
1149     }
1150 }
1151
1152 void DocClipBase::updateCutZone(int oldin, int oldout, int in, int out, QString desc)
1153 {
1154     QPoint old(oldin, oldout);
1155     for (int i = 0; i < m_cutZones.size(); ++i) {
1156         if (m_cutZones.at(i).zone == old) {
1157             CutZoneInfo info;
1158             info.zone = QPoint(in, out);
1159             info.description = desc;
1160             m_cutZones.replace(i, info);
1161             break;
1162         }
1163     }
1164 }
1165
1166 QList <CutZoneInfo> DocClipBase::cutZones() const
1167 {
1168     return m_cutZones;
1169 }
1170
1171 bool DocClipBase::hasVideoCodec(const QString &codec) const
1172 {
1173     Mlt::Producer *prod = NULL;
1174     if (m_baseTrackProducers.count() == 0) return false;
1175     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
1176         if (m_baseTrackProducers.at(i) != NULL) {
1177             prod = m_baseTrackProducers.at(i);
1178             break;
1179         }
1180     }
1181
1182     if (!prod) return false;
1183     int default_video = prod->get_int("video_index");
1184     char property[200];
1185     snprintf(property, sizeof(property), "meta.media.%d.codec.name", default_video);
1186     return prod->get(property) == codec;
1187 }
1188
1189 bool DocClipBase::hasAudioCodec(const QString &codec) const
1190 {
1191     Mlt::Producer *prod = NULL;
1192     if (m_baseTrackProducers.count() == 0) return false;
1193     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
1194         if (m_baseTrackProducers.at(i) != NULL) {
1195             prod = m_baseTrackProducers.at(i);
1196             break;
1197         }
1198     }
1199     if (!prod) return false;
1200     int default_video = prod->get_int("audio_index");
1201     char property[200];
1202     snprintf(property, sizeof(property), "meta.media.%d.codec.name", default_video);
1203     return prod->get(property) == codec;
1204 }
1205
1206
1207 void DocClipBase::slotExtractImage(QList <int> frames)
1208 {
1209     if (m_thumbProd == NULL) return;
1210     m_thumbProd->extractImage(frames);
1211 }
1212
1213 QImage DocClipBase::extractImage(int frame, int width, int height)
1214 {
1215     if (m_thumbProd == NULL) return QImage();
1216     QMutexLocker locker(&m_producerMutex);
1217     return m_thumbProd->extractImage(frame, width, height);
1218 }
1219
1220